import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Redirect } from "react-router-dom";
import { ClockCircleOutlined } from '@ant-design/icons';
import {
    Layout, Menu, Icon, Table, Divider, Button, Modal, Form, Input, DatePicker,
    Select, Popconfirm, message, Alert, TreeSelect, TimePicker, Tree, Upload,
    AutoComplete, Tabs, Col, Row, Dropdown, Card, Pagination, Spin, Skeleton,
    Drawer, Tag, Badge, Radio, Steps, Transfer, notification, Empty, Calendar, Checkbox, Switch, Space
} from "antd";
import { CloseOutlined, CheckOutlined } from '@ant-design/icons';
import {
    allUserApi, addUserApi, deleteUserApi, updateUserApi, SchoolAllApi, AttenceDepartentApi, loginApiToSurvey, uploadUserInfo, updateZhizhouPushTimeApi, updatePatrolPushTimeApi, updateInspectTypeApi, updateInspectPushTimeApi
} from "../js/api.js";
import {
    allBlueteethDeviceApi, addBlueTeethDeviceApi, batchIncreaseRelationApi, deleteBlueTeethDeviceApi,
    allAddressApi, addAddressApi, updateAddressApi, deleteAddressApi,
    allAddressInBlueteethRelationApi, getAddressWithBlueteethByAddressApi,
    deleteAddressWithBlueteethSingleApi, deleteAddressWithBlueteethMulApi,
    addAddressWithBlueteethMulApi, addAndUpdateAddressWithBlueteethSingleApi,
    getUsableAddressAndMacAddressApi, addInspectItemBySchoolIdApi, getBlueteethForRelationApi, patrolPlanBySchoolApi, addAttendanceTimeApi, getattendanceSettimeListApi,
} from "../js/api.js";
import { exportExcel } from "../js/utils.js";
import {
    getManualBySchoolAndCategoryApi, getUsableAddressAndMacAddressForZhizhouApi, getManualDetailBySchoolAndItemApi, deleteManualByItemApi, deleteManualByContentApi, deleteaddAttendanceTimeApi, getManualForUpdateApi, updateManualApi, getCategoryItemNumApi, getHistoryCheckApi,
} from "../js/api.js";
import {
    allMessagepushBySchoolApi, deleteMessagepushApi, addMessagepushApi, getAllPeopleBySchoolForMessagepush, allEventpushBySchoolApi, deleteEventpushApi, changeEventpushStateApi, addEventpushApi, allKaoQinPushBySchoolApi, deleteKaoQinPushApi, addKaoQinPushApi, allZhiZhouPushBySchoolApi, deleteZhiZhouPushApi, addZhiZhouPushApi
} from "../js/api.js";
import {
    getBlueteethApi, updateDistanceApi, updateUUIDApi, updateMajorApi, updateAttendanceTimeApi,
} from "../js/api.js";
import {
    listEmergencyContactApi, deleteEmergencyContactApi, listEmergencyContactOptionApi, insertEmergencyContactApi,
} from "../js/api.js";
import {
    listSafetyScenePushApi, saveSafetyScenePushApi
} from "../js/api.js";
import {
    allInspectpushBySchoolApi, addInspectpushApi, deleteInspectpushApi
} from "../js/api.js";
import {
    listMenuByPermission
} from "../js/api.js";
import {
    getScheduleTagApi, getScheduleDataApi, addScheduleTagApi, deleteScheduleTagApi, updateScheduleTagApi,
    getAttendanceRecordApi, getAttendanceSearchOptionDataApi, getAttendanceSearchChartDataApi
} from "../js/api.js";

import {
    uploadMultiRoutePatrolAddress, getMultiroutepatrolAddressBySchoolId, addMultiroutepatrolRoute,
    addMultiroutepatrolRouteName, getMultiRoutePatrolNameById, updateAddressAndRouteNameApi
} from "../js/api.js";
import { addressUploadTemplateUrl, userInfoUploadTemplateUrl, relationUploadTemplateUrl } from "../js/config.js";

import { deleteUserInfoAllApi } from "../js/api.js";

import { getAllIdentity, baseUrlSurvey } from "../js/config.js";
import { iconFontUrl } from "../js/config.js";
import { baseUrl } from "../js/config.js"
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
import icon from "../img/icon.png";
import md5 from 'md5';
import * as echarts from 'echarts'
// import echarts from 'echarts';
import { SignBlueteeth } from "./schoolattendance.jsx";
import '../css/pwd.css';
const TabPane = Tabs.TabPane;

const { Content, Footer, Sider, Header } = Layout;
const { TreeNode } = Tree;
const SubMenu = Menu.SubMenu;
const Step = Steps.Step;
const RangeTimePicker = TimePicker;


const format = 'HH:mm';

const RangePicker = DatePicker.RangePicker;
const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl,
});



class SchoolAdmin extends Component {
    constructor(props) {
        super(props);
        let url = document.location.href;
        let page = url.split("/")[5];
        let defaultSelectedKeys;
        let defaultOpenKeys;
        switch (page) {
            case "signblueteeth":
                defaultOpenKeys = "";
                defaultSelectedKeys = "signblueteeth"; break;
            case "user":
                defaultOpenKeys = "";
                defaultSelectedKeys = "user"; break;
            case "blueteethdevice":
                defaultOpenKeys = "checkpoint";
                defaultSelectedKeys = "blueteethdevice"; break;
            case "address":
                defaultOpenKeys = "checkpoint";
                defaultSelectedKeys = "address"; break;
            case "blueteethwithaddress":
                defaultOpenKeys = "checkpoint";
                defaultSelectedKeys = "blueteethwithaddress"; break;
            case "manual":
                defaultOpenKeys = "";
                defaultSelectedKeys = "manual"; break;
            case "dailypush":
                defaultOpenKeys = "messagepush";
                defaultSelectedKeys = "dailypush"; break;
            case "safetyscenepush":
                defaultOpenKeys = "messagepush";
                defaultSelectedKeys = "safetyscenepush"; break;
            case "inspectpush":
                defaultOpenKeys = "messagepush";
                defaultSelectedKeys = "inspectpush"; break;
            case "eventpush":
                defaultOpenKeys = "messagepush";
                defaultSelectedKeys = "eventpush"; break;
            case "blueteeth":
                defaultOpenKeys = "";
                defaultSelectedKeys = "blueteeth"; break;
            case "emergency":
                defaultOpenKeys = "";
                defaultSelectedKeys = "emergency"; break;
            default:
                defaultOpenKeys = "";
                defaultSelectedKeys = "user";
        }
        this.state = {
            defaultSelectedKeys: [defaultSelectedKeys],
            defaultOpenKeys: [defaultOpenKeys],
            collapsed: false,
            menuData: []
        };
        // console.log(this.props.location.state);
        //console.log(sessionStorage.getItem("username"));
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        let departmentId = sessionStorage.getItem("departmentId");
        let identityId = sessionStorage.getItem("identityId");
        listMenuByPermission(departmentId, identityId)
            .then(res => {
                this.setState({
                    menuData: res.data
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    onCollapse = (collapsed) => {
        //console.log(collapsed);
        if (collapsed) {
            document.getElementById("logoName").style.display = "none";
        } else {
            document.getElementById("logoName").style.display = "inline";
        }
        this.setState({ collapsed });
    }

    logOff() {
        sessionStorage.setItem("username", null);
        sessionStorage.setItem("identityId", null);
        sessionStorage.setItem("departmentId", null);
        this.props.history.push("/");
    }

    render() {
        const menu = this.state.menuData.map(val => {
            const subMenu = val.subMenu.map(subVal => {
                return (
                    <Menu.Item key={subVal.key}>
                        <Link to={subVal.route}>
                            <IconFont type={subVal.icon} className='icon' />
                            <span className="nav-text">{subVal.name}</span>
                        </Link>
                    </Menu.Item>
                )
            });
            return (
                val.subMenu.length == 0 ?
                    (
                        <Menu.Item key={val.key}>
                            <Link to={val.route}>
                                <IconFont type={val.icon} className='icon' />
                                <span className="nav-text">{val.name}</span>
                            </Link>
                        </Menu.Item>
                    ) :
                    (
                        <SubMenu
                            key={val.key}
                            title={
                                <span>
                                    <IconFont type={val.icon} className='icon' />
                                    <span>{val.name}</span>
                                </span>
                            }>
                            {subMenu}
                        </SubMenu>
                    )
            );
        });
        return (
            <Router basename="/school/admin">
                <Layout>
                    <Sider
                        collapsible
                        collapsed={this.state.collapsed}
                        onCollapse={this.onCollapse}
                        width={256}
                        style={{
                            overflow: "auto",
                            height: "100vh",
                            left: 0
                        }}>
                        <div className="logo" >
                            {/* <IconFont type="icon-anfang" className='icon' style={{ verticalAlign: "middle", }} /> */}
                            <img src={icon} className='icon' style={{
                                verticalAlign: 'middle',
                                width: '30px',
                                height: '30px',
                                marginRight: '5px'
                            }} />
                            <div
                                id='logoName'
                                style={{ verticalAlign: 'middle', display: 'inline-block', paddingLeft: "5px" }}>
                                梯度智慧安监
                            </div>
                        </div>
                        <Menu theme="dark" mode="inline" defaultSelectedKeys={this.state.defaultSelectedKeys} defaultOpenKeys={this.state.defaultOpenKeys}>
                            {menu}
                        </Menu>
                    </Sider>
                    <Layout style={{ height: "100vh" }}>
                        <Header style={{
                            background: '#fcfcfc',
                            padding: 0,
                            fontFamily: 'Microsoft Yahei, sans-serif',
                            fontSize: 15,
                            position: 'relative',
                            height: '64px',
                            lineHeight: '64px',
                        }}>
                            <div style={{ position: "absolute", top: 0, bottom: 0, left: 24, }}>
                                欢迎您！您的身份为<span style={{ color: '#1890ff' }}>管理员</span>
                            </div>

                            <div style={{ position: "absolute", top: 0, bottom: 0, right: 24, }}>
                                <Dropdown overlay={
                                    <Menu>
                                        <Menu.Item>
                                            <a
                                                class='logOff'
                                                style={{ color: '#333333', padding: '5px 15px' }}
                                                onClick={() => this.logOff()}>
                                                <IconFont
                                                    type="icon-zhuxiaologout11" className='icon'
                                                    style={{ fontSize: '14px', verticalAlign: 'middle' }} />
                                                <span style={{ verticalAlign: 'middle', marginLeft: '2px' }}>退出登录</span>
                                            </a>
                                        </Menu.Item>
                                    </Menu>
                                }>
                                    <div
                                        className='dropdown'
                                        style={{
                                            padding: '0px 5px'
                                        }}>
                                        <IconFont
                                            style={{ fontSize: '28px', verticalAlign: 'middle' }}
                                            type="icon-touxiang-shi" className='icon' />
                                        <span style={{ marginLeft: '2px' }}>{sessionStorage.getItem("username")}</span>
                                    </div>
                                </Dropdown>
                            </div>
                        </Header>
                        <Content style={{ margin: "24px", overflow: "initial" }}>
                            <div
                                id="right"
                                style={{
                                    padding: 24,
                                    background: "#fff",
                                    height: "auto",
                                    marginBottom: 24
                                }}
                            >
                                <Switch>
                                    <Route path="/user" component={SchoolUserManager} />
                                    {/* <Route path="/checkpoint" component={SchoolPointManager} /> */}
                                    <Route path="/blueteethdevice" component={BlueteethDeviceManager} />
                                    <Route path="/address" component={SchoolAddressManager} />
                                    <Route path="/blueteethwithaddress" component={AddressWithBlueteethManager} />
                                    <Route path="/manual" component={SchoolManualManager} />
                                    <Route path="/dailypush" component={SchoolMessagepushManager} />
                                    <Route path="/inspectpush" component={SchoolInspectpushManager} />
                                    <Route path="/safetyscenepush" component={SchoolSafetyscenePushManager} />
                                    <Route path="/eventpush" component={SchoolEventPushManager} />
                                    <Route path="/blueteeth" component={SchoolBlueTeethManager} />
                                    <Route path="/emergency" component={SchoolEmergencyManager} />
                                    <Route path="/signblueteeth" component={SignBlueteeth} />
                                    <Redirect path="/" to={{ pathname: '/user' }} />
                                </Switch>
                            </div>
                            <div
                                style={{
                                    width: 'auto',
                                    height: 24,
                                    background: '#f0f2f5'
                                }}
                            ></div>
                        </Content>
                    </Layout>
                </Layout>
            </Router>
        );
    }
}


class SchoolUserManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            addUserVisible: false, //控制新增用户模态框显示隐藏
            updateUserVisible: false, //控制修改用户信息模态框显示隐藏
            alertVisible: false, //提示用户名已存在
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            identityFilter: [],
            columnData: [],
            filteredInfo: null,
            sortedInfo: null,
            exportUserInfoVisible: false
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        allUserApi(3, sessionStorage.getItem("departmentId"))
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    columnData.push({
                        key: index + 1,
                        username: item.username,
                        name: item.realName,
                        phone: item.phone,
                        identity: item.identity,
                        department: item.department
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        let identityFilter = [];
        getAllIdentity('学校用户', parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    identityFilter.push({
                        text: item.identity,
                        value: item.identity
                    });
                });
                this.setState({
                    identityFilter: identityFilter,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

    }

    handleDelete(username) {
        deleteUserApi(username)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                }else if(res.data == 'delete_fail'){
                    message.error('该用户已加入巡检计划,不可以删除，如要删除，请先在班组设置里删除该用户!');
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    showModal() {//展示添加的modal
        this.setState({
            addUserVisible: true,
            exportUserInfoVisible: false
        });
    }
    //批量导入用户信息
    showExportModal() {
        this.setState({
            exportUserInfoVisible: true
        });
    }

    //点击表格中 修改、重置密码 触发的操作
    updateHandleClick(username, type, currentRealname, currentPhone, currentIdentity) {
        if (type == "update") {
            this.setState({
                modalTitle: "修改用户信息",
                modalType: "update",
                currentRealname: currentRealname,
                currentPhone: currentPhone,
                currentIdentity: currentIdentity,
            });
        } else if (type == "resetPSW") {
            this.setState({
                modalTitle: "重置密码",
                modalType: "resetPSW"
            });
        }
        this.setState({
            updateUserVisible: true,
            alertVisible: false,
            username: username,
            exportUserInfoVisible: false
        });
    }

    //新增用户 点击提交按钮后的操作
    addUserHandleClick() {
        this.setState({
            confirmLoading: true,
            exportUserInfoVisible: false
        });
        let val = this.refs.addUserFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                values.department = sessionStorage.getItem("departmentId");
                //console.log(values);
                addUserApi(values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                addUserVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "用户名已存在!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    //修改用户信息 点击提交按钮后的操作
    updateUserHandleClick(username) {
        this.setState({
            confirmLoading: true,
            exportUserInfoVisible: false
        });
        let val = this.refs.updateUserFormValue;
        val.validateFields((err, values) => {
            //console.log(values);
            //console.log(err);
            if (values.password != values.repassword) {
                this.setState({
                    alertVisible: true,
                    confirmLoading: false,
                    msg: "两次输入密码不一致,请重新输入!"
                });
            } else if (values.password == "" || values.repassword == "") {
                this.setState({
                    alertVisible: true,
                    confirmLoading: false,
                    msg: "密码不可为空,请重新输入!"
                });
            } else {
                values.department = sessionStorage.getItem("departmentId");
                //console.log(values);
                updateUserApi(username, values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                updateUserVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            message.success("更新成功!");
                            val.resetFields();
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                updateUserVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }

        });
    }

    //关闭 用户名已存在 的提示
    handleClose() {
        this.setState({ alertVisible: false, exportUserInfoVisible: false });
    }

    //关闭模态框
    handleCancel(modal) {
        this.setState({
            alertVisible: false,
            exportUserInfoVisible: false
        });
        if (modal == "addUser") {
            let val = this.refs.addUserFormValue;
            val.resetFields();
            this.setState({
                addUserVisible: false
            });
        }
        if (modal == "updateUser") {
            let val = this.refs.updateUserFormValue;
            val.resetFields();
            this.setState({
                updateUserVisible: false
            });
        }
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
            exportUserInfoVisible: false
        });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
            exportUserInfoVisible: false
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    handleDeleteUserInfo() {
        console.log("==========删除用户信息=================")
        let departmentId = sessionStorage.getItem("departmentId")
        deleteUserInfoAllApi(departmentId)
            .then((res) => {
                console.log("res=========", res)
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else if(res.data == 'delete_fail'){
                    message.error('删除失败,用户已存在巡检计划，若删除用户，请先删除巡检计划或巡检班组!');
                }else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //子组件调用父组件方法刷新数据
    getAllUser = (data) => {
        this.setState({
            columnData: data,
            exportUserInfoVisible: false
        });
    }

    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        // Excel标题
        let header = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "用户名",
                dataIndex: "username",
                key: "username"
            },
            {
                title: "姓名",
                dataIndex: "name",
                key: "name",
            }, {
                title: "联系电话",
                dataIndex: "phone",
                key: "phone"
            },
            {
                title: "用户类型",
                dataIndex: "identity",
                key: "identity"}]
        const userColumns = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "用户名",
                dataIndex: "username",
                key: "username"
            },
            {
                title: "姓名",
                dataIndex: "name",
                key: "name",
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.name.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            },
            {
                title: "联系电话",
                dataIndex: "phone",
                key: "phone"
            },
            {
                title: "用户类型",
                dataIndex: "identity",
                key: "identity",
                filters: this.state.identityFilter,
                filteredValue: filteredInfo.identity || null,
                onFilter: (value, record) => record.identity == value,
                filterIcon: filtered => <Icon type="filter" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            },
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        <a href="javascript:;" onClick={this.updateHandleClick.bind(this, record.username, "update", record.name, record.phone, record.identity)}>修改</a>
                        <Divider type="vertical" />
                        <a href="javascript:;" onClick={this.updateHandleClick.bind(this, record.username, "resetPSW", record.name, record.phone, record.identity)}>重置密码</a>
                        <Divider type="vertical" />
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                            onConfirm={() => this.handleDelete(record.username)}>
                            <a href="#">删除</a>
                        </Popconfirm>
                    </span>
                )
            }
        ];
        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" onClick={this.showModal.bind(this)} size="large">
                        <Icon type="user-add" />新增用户
                    </Button>
                    <Button style={{ marginLeft: '20px' }} type="primary" onClick={this.showExportModal.bind(this)} size="large">
                        <Icon type="plus" />批量导入
                    </Button>

                    <Button href={userInfoUploadTemplateUrl} style={{ marginLeft: '20px' }}><Icon type="download" />下载模板</Button>
                    <ExportUserInfo visible={this.state.exportUserInfoVisible} getAllUser={this.getAllUser} />
                    <Button style={{ marginLeft: '20px' }} onClick={this.clearAll}>
                        <Icon type="delete" theme="outlined" />清除筛选
                    </Button>

                    <Button style={{ marginLeft: '20px' }} type="primary">
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                            onConfirm={() => this.handleDeleteUserInfo()}>
                            <a href="#"><Icon Icon type="delete" theme="outlined" />批量删除</a>
                        </Popconfirm>
                    </Button>
                    <Button type="primary" style={{ marginLeft: 8 }} onClick={() =>  {
                                    exportExcel(header, this.state.columnData, "用户名单.xlsx")
                                    }}>用户名单导出Excel
                    </Button>

                    <Modal
                        title="新增用户"
                        visible={this.state.addUserVisible}
                        onCancel={this.handleCancel.bind(this, "addUser")}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large"
                                loading={this.state.confirmLoading}
                                onClick={this.addUserHandleClick.bind(this)}>提交</Button>
                        ]}
                    >
                        <AddUserForm ref="addUserFormValue" />
                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                    <Modal
                        title={this.state.modalTitle}
                        visible={this.state.updateUserVisible}
                        onCancel={this.handleCancel.bind(this, "updateUser")}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large"
                                loading={this.state.confirmLoading}
                                onClick={this.updateUserHandleClick.bind(this, this.state.username)}>提交</Button>
                        ]}
                    >
                        {
                            (this.state.modalType == "resetPSW") ?
                                (<ResetPSWForm ref="updateUserFormValue" type={this.state.modalType} />) :
                                (<UpdateUserForm ref="updateUserFormValue" type={this.state.modalType}
                                    currentRealname={this.state.currentRealname} currentPhone={this.state.currentPhone}
                                    currentIdentity={this.state.currentIdentity} />)
                        }
                        {
                            this.state.alertVisible ?
                                (
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                        }
                    </Modal>
                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={userColumns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 30, 100]
                    }} />
            </div>
        );
    }
}
class exportUserInfo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: props.visible,
            fileList: [],
            uploading: false,
            isExport: false,
            msg: ''
        }
    }
    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
        });
    }
    handleAddCancel() {
        console.log("----------------关闭")
        let columnData = []
        allUserApi(3, sessionStorage.getItem("departmentId"))
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        username: item.username,
                        name: item.realName,
                        phone: item.phone,
                        identity: item.identity,
                        department: item.department
                    });
                });
                this.props.getAllUser(columnData);
            })
        this.setState({
            visible: false,
            fileList: [],
            isExport: false,
            uploading: false,
            msg: ''
        });

    }
    handleUpload = () => {
        console.log("----------------上传")
        const { fileList } = this.state;
        const formData = new FormData();
        fileList.forEach(file => {
            formData.append('upfile', file);
        });
        formData.append('schoolId', sessionStorage.getItem("departmentId"))
        this.setState({
            uploading: true,
            msg: ''
        });
        uploadUserInfo(formData).then((res) => {
            console.log("upload", res.data)
            if (res.data.msg == "success") {
                this.setState({
                    uploading: false,
                    fileList: [],
                    isExport: true,
                    msg: "导入成功!"
                });
                message.success("导入成功!");
            } else if (res.data.msg == "fail") {
                this.setState({
                    uploading: false,
                    fileList: [],
                    isExport: true,
                    msg: "上传失败!"
                });
                message.warning("导入失败!");
            } else{
                const duplicateNames = res.data.msg
                let message1 = ''
                duplicateNames.forEach((item) => {
                    message1 += "用户名 " + item.username + " 存在重复!" + item.name + "\r\n"
                })
                
                this.setState({
                    uploading: false,
                    fileList: [],
                    isExport: true,
                    msg: message1
                });
                message.warning("导入失败!");
            }
        })

    };
    render() {
        const { uploading, fileList } = this.state;
        const props = {
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: file => {
                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));
                return false;
            },
            fileList,
        };
        let drawerContent;
        let footerButton
        drawerContent = (
            <div style={{ textAlign: 'center' }}>
                <div style={{ color: 'gray' }}>
                    请选择需要导入的用户信息
                </div>
                <Upload {...props}>
                    <Button type="primary" style={{ marginTop: 15 }}>选择文件</Button>
                </Upload>
                <Button
                    type="primary"
                    onClick={this.handleUpload}
                    disabled={fileList.length === 0}
                    loading={uploading}
                    style={{ marginTop: 20 }}
                >
                    {uploading ? '正在导入' : '导入用户'}
                </Button>
                <div style={{ color: 'red', marginTop: 20, fontSize: 18, whiteSpace: 'pre-wrap'}}>
                    {this.state.isExport ? this.state.msg : ''}
                </div>
            </div>
        )
        footerButton = (
            <div>
                <Button size="large" onClick={this.handleAddCancel.bind(this)}
                    style={{ marginRight: 20 }}>关闭</Button>
            </div>
        )
        return (
            <Drawer
                bodyStyle={{ paddingBottom: 100, paddingRight: 50 }}
                width={500}
                title={'批量导入用户信息'}
                visible={this.state.visible}
                onClose={this.handleAddCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                {drawerContent}
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    {footerButton}
                </div>
            </Drawer>
        )
    }
}
const ExportUserInfo = Form.create()(exportUserInfo)

const FormItem = Form.Item;
const Option = Select.Option;
class addUserForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            allDepartment: [],
            allIdentity: []
        };
    }

    componentDidMount() {
        let allIdentity = [];
        getAllIdentity("学校用户", parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log(item);
                    allIdentity.push({
                        value: item.id,
                        text: item.identity
                    });
                });
                this.setState({
                    allIdentity: allIdentity
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
        //-----上是用户类型，下是单位，学校用户的单位唯一
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const allIdentityOptions = this.state.allIdentity.map(d => <Option key={d.value}>{d.text}</Option>);
        //console.log(allIdentityOptions);
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };

        return (
            <Form>
                <FormItem
                    label='用户名'
                    {...formItemLayout}>
                    {getFieldDecorator("userName", {
                        initialValue: "",
                        rules: [{
                            required: true,
                            message: "请输入用户名!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="用户名"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='密码'
                    {...formItemLayout}>
                    {getFieldDecorator("password", {
                        initialValue: "",
                        rules: [{
                            required: true,
                            message: "请输入密码!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            type="password"
                            placeholder="密码"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='真实姓名'
                    {...formItemLayout}>
                    {getFieldDecorator("realName", {
                        initialValue: "",
                        rules: [{
                            required: true,
                            message: "请输入真实姓名!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="真实姓名"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='联系电话'
                    {...formItemLayout}>
                    {getFieldDecorator("phone", {
                        initialValue: "",
                        rules: [{
                            required: true,
                            message: "请输入联系电话!"
                        }]
                    })(
                        <Input
                            size="large"
                            prefix={
                                <Icon type="mobile" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="联系电话"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='用户类型'
                    {...formItemLayout}>
                    {getFieldDecorator("identity", {
                        rules: [{
                            required: true,
                            message: "请输入用户类型!"
                        }]
                    })(
                        <Select
                            size="large"
                            placeholder="用户类型">
                            {allIdentityOptions}
                        </Select>
                    )}
                </FormItem>
            </Form>
        );
    }
}
const AddUserForm = Form.create()(addUserForm);

class updateUserForm extends Component {
    constructor(props) {
        super(props);
        if (this.props.type == "update") {
            this.state = {
                allIdentity: [],
                update: "",
                resetPSW: "none",
                currentRealname: props.currentRealname,
                currentPhone: props.currentPhone,
                currentIdentity: props.currentIdentity
            };
        } else if (this.props.type == "resetPSW") {
            this.state = {
                allIdentity: [],
                update: "none",
                resetPSW: ""
            };
        }
    }

    componentWillReceiveProps(props) {
        //console.log(props);
        if (this.props.type == "update") {
            this.setState({
                currentRealname: props.currentRealname,
                currentPhone: props.currentPhone,
                currentIdentity: props.currentIdentity
            });

        }
    }

    componentDidMount() {
        let allIdentity = [];
        getAllIdentity("学校用户", parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    allIdentity.push({
                        value: item.id,
                        text: item.identity
                    });
                });
                this.setState({
                    allIdentity: allIdentity
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const allIdentityOptions = this.state.allIdentity.map((d, index) => <Option value={d.value} key={index}>{d.text}</Option>);

        let currentIdentityId = '';
        for (let i = 0; i < this.state.allIdentity.length; i++) {
            if (this.state.allIdentity[i].text == this.state.currentIdentity) {
                currentIdentityId = this.state.allIdentity[i].value
                break;
            }
        }
        //console.log(this.state);
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };

        return (
            <Form>
                <div style={{ display: this.state.resetPSW }}>
                    <FormItem
                        label='新密码'
                        {...formItemLayout}>
                        {getFieldDecorator("password", {
                            rules: [{
                                required: true,
                                message: '请输入新密码！',
                            }]
                        })(
                            <Input
                                size="large"
                                prefix={
                                    <Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />
                                }
                                type="password"
                                placeholder="请输入新密码"
                            />
                        )}
                    </FormItem>
                    <FormItem
                        label='重复密码'
                        {...formItemLayout}>
                        {getFieldDecorator("repassword", {
                            rules: [{
                                required: true,
                                message: '请重复输入新密码！',
                            }]
                        })(
                            <Input
                                size="large"
                                prefix={
                                    <Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />
                                }
                                type="password"
                                placeholder="请重复密码"
                            />
                        )}
                    </FormItem>
                </div>
                <div style={{ display: this.state.update }}>
                    <FormItem
                        label='真实姓名'
                        {...formItemLayout}>
                        {getFieldDecorator("realName", {
                            initialValue: this.state.currentRealname,
                            rules: [{
                                required: true,
                                message: '请输入修改后的姓名！',
                            }]
                        })(
                            <Input
                                size="large"
                                prefix={
                                    <Icon type="idcard" style={{ color: "rgba(0,0,0,.25)" }} />
                                }
                                placeholder="请输入真实姓名"
                            />
                        )}
                    </FormItem>
                    <FormItem
                        label='联系电话'
                        {...formItemLayout}>
                        {getFieldDecorator("phone", {
                            initialValue: this.state.currentPhone,
                            rules: [{
                                required: true,
                                message: '请输入修改后的联系电话！',
                            }]
                        })(
                            <Input
                                size="large"
                                prefix={
                                    <Icon type="mobile" style={{ color: "rgba(0,0,0,.25)" }} />
                                }
                                placeholder="请输入联系电话"
                            />
                        )}
                    </FormItem>
                    <FormItem
                        label='用户类型'
                        {...formItemLayout}>
                        {getFieldDecorator("identity", {
                            initialValue: currentIdentityId,
                            rules: [{
                                required: true,
                                message: '请选择修改后的用户类型！',
                            }]
                        })(
                            <Select size="large" placeholder="请选择用户类型" >
                                {allIdentityOptions}
                            </Select>
                        )}
                    </FormItem>
                </div>
            </Form>
        );
    }
}
const UpdateUserForm = Form.create()(updateUserForm);

const ResetPSWForm = Form.create()(updateUserForm);

//-----------------------------------------------------------------------------------------------

class BlueteethDeviceManager extends Component {
    constructor(props) {
        super(props);

        this.state = {
            addVisible: false,
            alertVisible: false,
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            data: [],
            filteredInfo: null,
            sortedInfo: null,
            nowMajor: undefined,
            usedFilter: [{
                text: '使用中',
                value: 1
            }, {
                text: '备用',
                value: 0
            }]
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        allBlueteethDeviceApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    // console.log("item.macAddress", item.macAddress.split(':').legnth);
                    if (item.macAddress.split(':').length == 3) {
                        let macAddressId = (item.macAddress.split(':'))[1];
                        columnData.push({
                            key: index + 1,
                            id: item.id,
                            macAddress: item.macAddress,
                            macAddressId: macAddressId,
                            devicePower: item.devicePower,
                            createTime: item.createTime,
                            category: item.category,
                            deviceName: item.deviceName,
                            validTime: item.validTime,
                            used: item.used,
                            type: item.type,
                        });
                    } else {
                        columnData.push({
                            key: index + 1,
                            id: item.id,
                            macAddress: item.macAddress,
                            macAddressId: item.macAddress,
                            devicePower: item.devicePower,
                            createTime: item.createTime,
                            category: item.category,
                            deviceName: item.deviceName,
                            validTime: item.validTime,
                            used: item.used,
                            type: item.type,
                        });
                    }
                });

                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        getBlueteethApi(sessionStorage.getItem("departmentId"))
            .then((res) => {
                this.setState({
                    nowMajor: res.data.major,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    //点击表格中 添加 触发的操作
    showAddModal() {
        this.setState({
            addVisible: true,
        });
    }

    addHandleClick() {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addBlueteethDeviceFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                values.macAddress = this.state.nowMajor + ':' + values.macAddress + ':' + sessionStorage.getItem("departmentId");
                addBlueTeethDeviceApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                alertVisible: false,
                                addVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "repeat") {
                            this.setState({
                                alertVisible: true,
                                addVisible: true,
                                confirmLoading: false,
                                msg: "设备编号已存在，请更换!"
                            });
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                addVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    handleDelete(id, used) {
        if (used) {
            notification['error']({
                message: '删除失败！',
                description: '此硬件设备已在使用中。若要删除，请先删除设备与检查点的关联',
            });
        } else {
            deleteBlueTeethDeviceApi(id, parseInt(sessionStorage.getItem("departmentId")))
                .then((res) => {
                    if (res.data == "success") {
                        message.success("删除成功!");
                        this.refreshData();
                    } else {
                        message.error('删除失败,请稍后再试!');
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
        }

    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    handleAddCancel() {
        let val = this.refs.addBlueteethDeviceFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            addVisible: false
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        let columns = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            }, {
                title: "设备编号",
                dataIndex: "macAddressId",
                key: "macAddressId",
                sorter: (a, b) => {
                    if (a.macAddressId < b.macAddressId) {
                        return -1;
                    } else if (a.macAddressId > b.macAddressId) {
                        return 1;
                    } else {
                        return 0;
                    }
                },
                sortOrder: sortedInfo.columnKey === 'macAddress' && sortedInfo.order,
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.macAddressId.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            }, {
                title: "电量",
                dataIndex: "devicePower",
                key: "devicePower",
                sorter: (a, b) => parseInt(a.devicePower) - parseInt(b.devicePower),
                sortOrder: sortedInfo.columnKey === 'devicePower' && sortedInfo.order,
                render: (text) => {
                    if (parseInt(text) < 0) {
                        return <Tag color='red'>未能检测到</Tag>
                    } else {
                        return (
                            <div>
                                <img
                                    style={{ width: '30px', height: '30px' }}
                                    src={require('../img/battery' + parseInt(text / 20) + '.png')} />{text + '% '}
                            </div>)
                    }
                }
            }, {
                title: "使用情况",
                dataIndex: "used",
                key: "used",
                filters: this.state.usedFilter,
                filteredValue: filteredInfo.used || null,
                onFilter: (value, record) => record.used == value,
                filterIcon: filtered => <Icon type="filter" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                render: (text, record) => (
                    <div>
                        {record.used == 0 ?
                            (<Tag color={'#108ee9'}>备用</Tag>) : (<Tag color={'#87d068'}>使用中</Tag>)}
                    </div>
                )
            }, {
                title: "入库时间",
                dataIndex: "createTime",
                key: "createTime",
                sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
                sortOrder: sortedInfo.columnKey === 'createTime' && sortedInfo.order,
            },
            {
                title: "设备类型",
                dataIndex: "type",
                key: "type",
                render:(text, record)=>(
                    <div>
                        {record.type == 0 ?
                            (<Tag color={'#108ee9'}>蓝牙</Tag>) : (<Tag color={'#87d068'}>NFC</Tag>)}
                    </div>
                )
            },
            {
                title: "有效日期",
                dataIndex: "validTime",
                key: "validTime",
            },
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => {
                    return (
                        <span>
                            <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                                onConfirm={() => this.handleDelete(record.id, record.used)}>
                                <a href="#">删除</a>
                            </Popconfirm>
                        </span>
                    )
                }
            }
        ];

        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    {
                        this.state.addVisible ? (
                            <Modal
                                title={"新增硬件设备"}
                                visible={this.state.addVisible}
                                onCancel={this.handleAddCancel.bind(this)}
                                closable
                                footer={[
                                    <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                        onClick={this.addHandleClick.bind(this)}>提交</Button>
                                ]}
                            >
                                <AddBlueteethDeviceForm ref="addBlueteethDeviceFormValue"
                                    nowMajor={this.state.nowMajor} />
                                {
                                    this.state.alertVisible ?
                                        (
                                            <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                        ) : null
                                }
                            </Modal>) : null
                    }
                    <Button type="primary" onClick={this.showAddModal.bind(this)} size="large">
                        <Icon type="plus" theme="outlined" />新增硬件设备
                    </Button>
                    <Button style={{ marginLeft: '20px' }} onClick={this.clearAll}>
                        <Icon type="delete" theme="outlined" />清除筛选与排序
                    </Button>
                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        )
    }
}


class addBlueteethDeviceForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            nowMajor: props.nowMajor,
            confirmLoading: false,
        }
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        };

        return (
            <Form>
                <FormItem
                    label='设备编号'
                    {...formItemLayout}>
                    {getFieldDecorator("macAddress", {
                        //initialValue: this.state.currentAddress,
                        rules: [{
                            required: true,
                            pattern: new RegExp(/^[1-9]\d*$/, "g"),
                            message: '请输入正确的设备编号',
                        }]
                    })(
                        <Input
                            addonBefore={this.state.nowMajor + ":"}
                            addonAfter={':' + sessionStorage.getItem("departmentId")}
                            size="large"
                            placeholder="请输入设备编号"
                        />
                    )}
                </FormItem>
            </Form>
        )
    }
}
const AddBlueteethDeviceForm = Form.create()(addBlueteethDeviceForm);

class SchoolAddressManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            addVisible: false,
            updateVisible: false,
            alertVisible: false,
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            data: [],
            filteredInfo: null,
            sortedInfo: null,
            typeFilter: [
                { text: '巡更', value: 1 },
                { text: '巡检', value: 2 },
                { text: '值周', value: 3 },
                // { text: 'NFC', value: 4 },
            ],
            exportCheckPointVisible: false,
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        allAddressApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        address: item.address,
                        type: item.type,
                        createTime: item.createTime,
                    });
                });

                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    //点击表格中 添加 触发的操作
    showAddModal() {
        this.setState({
            addVisible: true,
            exportCheckPointVisible: false
        });
    }

    showUpdateModal(id, address, type) {
        this.setState({
            exportCheckPointVisible: false,
            updateVisible: true,
            currentId: id,
            currentAddress: address,
            currentType: type
        });
    }

    addHandleClick() {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addAddressFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                addAddressApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                addVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "repeat") {
                            this.setState({
                                alertVisible: true,
                                addVisible: true,
                                confirmLoading: false,
                                msg: "地址名称已存在，请更换!"
                            });
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                addVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    updateHandleClick(id) {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.updateAddressFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                updateAddressApi(id,
                    parseInt(sessionStorage.getItem("departmentId")), values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                alertVisible: false,
                                updateVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            message.success("更新成功!");
                            val.resetFields();
                        } else if (res.data == "repeat") {
                            this.setState({
                                alertVisible: true,
                                updateVisible: true,
                                confirmLoading: false,
                                msg: "地址名称已存在，请更换!"
                            });
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                updateVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    handleDelete(id, type) {
        deleteAddressApi(id, parseInt(sessionStorage.getItem("departmentId")), type)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    //关闭模态框
    handleUpdateCancel() {
        let val = this.refs.updateAddressFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            updateVisible: false
        });
    }

    handleAddCancel() {
        let val = this.refs.addAddressFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            addVisible: false
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
            exportCheckPointVisible: false
        });
    }
    //新增showMulRouteModal
    // showMulRouteModal = () => {
    //     console.log("---------------route")
    //     this.setState({
    //         exportMulRouteVisible: true
    //     })
    // }
    showCheckPointModal = () => {
        console.log("---------------export")
        this.setState({
            exportCheckPointVisible: true
        })
    }
    //子组件调用父组件方法刷新数据
    getAllAddress = (data) => {
        this.setState({
            columnData: data,
            exportCheckPointVisible: false
        });
    }

    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "检查点地址",
            dataIndex: "address",
            key: "address",
            sorter: (a, b) => {
                if (a.address < b.address) {
                    return -1;
                } else if (a.address > b.address) {
                    return 1;
                } else {
                    return 0;
                }
            },
            sortOrder: sortedInfo.columnKey === 'address' && sortedInfo.order,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.address.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "类型",
            dataIndex: "type",
            key: "type",
            render: (text) => {
                if (text == 1) {
                    return (
                        <div>
                            <Tag color={'magenta'}>{'巡更'}</Tag>
                        </div>
                    )
                }
                else if (text == 2) {
                    return (
                        <div>
                            <Tag color={'blue'}>{'巡检'}</Tag>
                        </div>
                    )
                }
                else if (text == 3) {
                    return (
                        <div>
                            <Tag color={'green'}>{'值周'}</Tag>
                        </div>
                    )
                }
                // else if (text == 4) {
                //     return (
                //         <div>
                //             <Tag color={'#E2C07F'}>{'NFC'}</Tag>
                //         </div>
                //     )
                // }
            },
            filters: this.state.typeFilter,
            filteredValue: filteredInfo.type || null,
            onFilter: (value, record) => record.type == value,
            filterIcon: filtered => <Icon type="filter" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
        }, {
            title: "操作详情",
            key: "action",
            render: (text, record) => {
                if (record.type == 2) {
                    return (
                        <span>
                            <a href="javascript:;"
                                onClick={this.showUpdateModal.bind(this, record.id,
                                    record.address, record.type)}>修改地址</a>
                            <Divider type="vertical" />
                            <Popconfirm
                                title="若删除，则会删除与之相关的信息！仍然确定删除？"
                                okText="确定"
                                cancelText="取消"
                                placement="left"
                                icon={<Icon type="exclamation-circle" style={{ color: 'red' }} />}
                                onConfirm={() => this.handleDelete(record.id, record.type)}>
                                <a href="#">删除</a>
                            </Popconfirm>
                        </span>
                    )
                } else {
                    return (
                        <span>
                            <a href="javascript:;"
                                onClick={this.showUpdateModal.bind(this, record.id,
                                    record.address, record.type)}>修改地址</a>
                            <Divider type="vertical" />
                            <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                                onConfirm={() => this.handleDelete(record.id, record.type)}>
                                <a href="#">删除</a>
                            </Popconfirm>
                        </span>
                    )
                }
            }
        }];
        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    {
                        this.state.updateVisible ? (
                            <Modal
                                title={"修改检查点地址"}
                                visible={this.state.updateVisible}
                                onCancel={this.handleUpdateCancel.bind(this)}
                                closable
                                footer={[
                                    <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                        onClick={this.updateHandleClick.bind(
                                            this, this.state.currentId)}>提交</Button>
                                ]}
                            >
                                <UpdateAddressForm ref="updateAddressFormValue"
                                    currentAddress={this.state.currentAddress}
                                    currentType={this.state.currentType} />
                                {
                                    this.state.alertVisible ?
                                        (
                                            <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                        ) : null
                                }
                            </Modal>) : null
                    }
                    {
                        this.state.addVisible ? (
                            <Modal
                                title={"新增检查点地址"}
                                visible={this.state.addVisible}
                                onCancel={this.handleAddCancel.bind(this)}
                                closable
                                footer={[
                                    <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                        onClick={this.addHandleClick.bind(this)}>提交</Button>
                                ]}
                            >
                                <AddAddressForm ref="addAddressFormValue" />
                                {
                                    this.state.alertVisible ?
                                        (
                                            <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                        ) : null
                                }
                            </Modal>) : null
                    }
                    <Button type="primary" onClick={this.showAddModal.bind(this)} size="large">
                        新增检查点
                    </Button>
                    <Button type="primary" size="large" onClick={this.showCheckPointModal.bind(this)} style={{ marginLeft: 15 }}>
                        <Icon type="plus" theme="outlined" />网点导入
                    </Button>
                    <Button href={addressUploadTemplateUrl} style={{ marginLeft: 15 }}><Icon type="download" />下载模板</Button>
                    <Button style={{ marginLeft: '20px' }} onClick={this.clearAll}>
                        <Icon type="delete" theme="outlined" />清除筛选与排序
                    </Button>
                    <ExportCheckPoint visible={this.state.exportCheckPointVisible} getAllAddress={this.getAllAddress} />
                    {/* <ExportMultiRoutePatrolForm visible={this.state.exportMulRouteVisible} /> */}

                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        )
    }
}
//新增网点导入
class ExportCheckPoint extends Component {
    constructor(props) {
        super(props)
        this.state = {
            visible: props.visible,
            fileList: [],
            uploading: false,
            isExport: false,
        }
    }
    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
        });
    }

    handleAddCancel() {
        console.log("----------------关闭")
        let columnData = [];
        allAddressApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        address: item.address,
                        type: item.type,
                        createTime: item.createTime,
                    });
                });
                this.props.getAllAddress(columnData);
            })
        this.setState({
            visible: false,
            fileList: [],
            isExport: false,
            uploading: false,
            msg: ''
        });
    }
    handleUpload = () => {
        const { fileList } = this.state;
        const formData = new FormData();
        fileList.forEach(file => {
            formData.append('upfile', file);
        });
        formData.append('schoolId', sessionStorage.getItem("departmentId"))
        this.setState({
            uploading: true,
            msg: ''
        });
        uploadMultiRoutePatrolAddress(formData).then((res) => {
            //console.log( "111", res.data)
            if (res.data == "success") {
                this.setState({
                    uploading: false,
                    fileList: [],
                    isExport: true,
                    msg: "导入成功!"
                });
                message.success("导入成功!");
            } else if (res.data == "repeat") {
                // message.success("网点名称存在重复，请重新导入!");
                this.setState({
                    uploading: false,
                    fileList: [],
                    isExport: true,
                    msg: "网点名称已存在,请重新导入!"
                });
                message.error("导入失败!");
            }
            else if (res.data == "fail") {
                this.setState({
                    uploading: false,
                    fileList: [],
                    isExport: true,
                    msg: "上传失败!"
                });
                message.warning("导入失败!");
            }
        })
    };

    render() {
        const { uploading, fileList } = this.state;
        const props = {
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: file => {
                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));
                return false;
            },
            fileList,
        };
        let drawerContent;
        let footerButton
        drawerContent = (
            <div style={{ textAlign: 'center' }}>
                <div style={{ color: 'gray' }}>
                    请选择需要导入的网点
                </div>
                <Upload {...props}>
                    <Button type="primary" style={{ marginTop: 15 }}>选择文件</Button>
                </Upload>
                <Button
                    type="primary"
                    onClick={this.handleUpload}
                    disabled={fileList.length === 0}
                    loading={uploading}
                    style={{ marginTop: 20 }}
                >
                    {uploading ? '正在导入' : '导入网点'}
                </Button>
                <div style={{ color: 'red', marginTop: 20, fontSize: 18 }}>
                    {this.state.isExport ? this.state.msg : ''}
                </div>
            </div>
        )
        footerButton = (
            <div>
                <Button size="large" onClick={this.handleAddCancel.bind(this)}
                    style={{ marginRight: 20 }}>关闭</Button>
            </div>
        )
        return (
            <Drawer
                bodyStyle={{ paddingBottom: 100, paddingRight: 50 }}
                width={500}
                title={'批量导入网点'}
                visible={this.state.visible}
                onClose={this.handleAddCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                {drawerContent}
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    {footerButton}
                </div>
            </Drawer>
        )
    }


}

class exportMultiRoutePatrolForm extends Component {
    constructor(props) {
        super(props)
        this.state = {
            visible: props.visible,
            currentStep: 0,
            fileList: [],
            treeData: [],
            expandedKeys: [],
            checkedKeys: [],
            addressIdList: [],
            selectedKeys: [],
            // autoExpandParent: true,
            uploading: false,
            confirmLoading: false,
            isExport: false,
            patrolAddress: []
        }
    }
    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
        });
    }
    handleAddCancel() {
        console.log("----------------关闭")
        this.setState({
            visible: false,
            confirmLoading: false,
            isExport: false,
            currentStep: 0,
            fileList: []
        });
    }
    //下一步
    next = (e) => {
        console.log("-------下一步")
        if (!this.state.isExport) {
            this.setState({
                confirmLoading: true
            })
        } else {
            this.setState({
                uploading: false,
                confirmLoading: false,
                isExport: true,
                currentStep: 1
            });
            let patrolAddress = []
            getMultiroutepatrolAddressBySchoolId(sessionStorage.getItem("departmentId")).then((res) => {
                console.log("address", res.data)
                res.data.patrolAddress.forEach((item, index) => {
                    patrolAddress.push({
                        title: item.name,
                        key: item.id
                    })
                })
                this.setState({
                    patrolAddress: patrolAddress
                })
            })
        }
    }
    next2 = (e) => {
        let schoolId = sessionStorage.getItem("departmentId");
        console.log("-------下一步2")
        this.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('values', values);
                addMultiroutepatrolRouteName(schoolId, values.routeName).then((res) => {
                    let routeNameId = res.data
                    addMultiroutepatrolRoute(schoolId, routeNameId, this.state.addressIdList).then((res) => {
                        if (res.data == 'success') {
                            this.setState({
                                currentStep: 2
                            })
                        }
                        message.success("提交成功!")
                    })
                })

            }
        });

    }
    prev = (e) => {
        console.log("-------上一步")
        this.setState({
            currentStep: 0,
        })
    }
    handleUpload = () => {
        const { fileList } = this.state;
        const formData = new FormData();
        fileList.forEach(file => {
            formData.append('upfile', file);
        });
        formData.append('schoolId', sessionStorage.getItem("departmentId"))
        this.setState({
            uploading: true,
        });
        uploadMultiRoutePatrolAddress(formData).then((res) => {
            console.log("upload", res.data)
            if (res.data == "success") {
                this.setState({
                    uploading: false,
                    confirmLoading: false,
                    isExport: true
                });
                message.success("导入成功!");
            }

        })
    };
    onCheck = (checkedKeys) => {
        let addressIdList = []
        checkedKeys.forEach((item, index) => {
            if (item != '0') {
                addressIdList.push(item)
            }
        })
        console.log('addressIdList', addressIdList);
        this.setState({
            addressIdList: addressIdList
        })
    }

    render() {
        const treeData = [
            {
                title: '所有巡更地址',
                key: '0',
                children:
                    this.state.patrolAddress
            }
        ]
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };
        const { uploading, fileList } = this.state;
        const props = {
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: file => {
                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));
                return false;
            },
            fileList,
        };
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let stepPatrol = (
            <Steps
                current={this.state.currentStep}
                style={{
                    marginBottom: 30,
                }}>
                <Step title="Excel巡更地址导入" description="请导入并选择下一步" />
                <Step title="分配多巡更路线" description="请分配并提交" />
                <Step title="完成" />
            </Steps>
        );
        let drawerContent;
        let footerButton
        if (this.state.currentStep == 0) {
            drawerContent = (
                <div style={{ textAlign: 'center' }}>
                    <div>
                        请选择需要导入的巡更地址Excel
                    </div>
                    <Upload {...props}>
                        <Button type="primary" style={{ marginTop: 15 }}>选择文件</Button>
                    </Upload>
                    <Button
                        type="primary"
                        onClick={this.handleUpload}
                        disabled={fileList.length === 0}
                        loading={uploading}
                        style={{ marginTop: 20 }}
                    >
                        {uploading ? '正在导入' : '导入地址'}
                    </Button>
                </div>
            )
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large" onClick={this.next} loading={this.state.confirmLoading}>下一步</Button>
                </div>
            )
        } else if (this.state.currentStep == 1) {
            drawerContent = (
                <Form onSubmit={this.next2}>
                    <FormItem
                        label='巡更路线名称'
                        {...formItemLayout}>
                        {getFieldDecorator("routeName", {
                            rules: [{
                                required: true,
                                message: "请定义巡更路线名称"
                            }]
                        })(
                            <Input
                                size="middle"
                                placeholder="巡更路线名称">
                            </Input>
                        )}
                    </FormItem>
                    <Tree
                        checkable
                        selectable={true}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.addressIdList}
                        treeData={treeData}
                    />
                </Form>
            )
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large" onClick={this.prev}
                        style={{ marginRight: 20 }} >上一步</Button>
                    <Button type="primary" size="large"
                        onClick={this.next2}>提交</Button>
                </div>
            )
        } else if (this.state.currentStep == 2) {
            drawerContent = (
                <div>
                    <div style={{
                        textAlign: 'center',
                        width: '100%',
                        marginTop: 200,
                    }}>
                        <IconFont type='icon-locationiconsuccess' style={{ fontSize: '10em' }} />
                        <div style={{ fontSize: 20 }}>操作成功</div>
                    </div>
                </div>
            )
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                </div>
            )
        }
        return (
            <Drawer
                bodyStyle={{ paddingBottom: 100, paddingRight: 50 }}
                width={800}
                title={'批量导入网点'}
                visible={this.state.visible}
                onClose={this.handleAddCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                <Skeleton loading={this.state.confirmLoading} active>
                    {stepPatrol}
                    {drawerContent}
                </Skeleton>
                {/* <Skeleton loading={this.state.confirmLoading} active>
                    {drawerContent}
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Skeleton> */}
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    {footerButton}
                </div>
            </Drawer>
        )
    }
}
const ExportMultiRoutePatrolForm = Form.create()(exportMultiRoutePatrolForm);

class addAddressForm extends Component {
    constructor(props) {
        super(props);

        this.state = {
            allAddressType: [{
                value: 1,
                text: '巡更'
            }, {
                value: 2,
                text: '巡检'
            }, {
                value: 3,
                text: '值周'
            }],
            confirmLoading: false,
        }
    }

    render() {
        const { getFieldDecorator } = this.props.form;

        const allAddressTypeOptions = this.state.allAddressType.map((d, index) =>
            <Option value={d.value} key={index}>{d.text}</Option>);

        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        };

        return (
            <Form>
                <FormItem
                    label='类型'
                    {...formItemLayout}>
                    {getFieldDecorator("type", {
                        rules: [{
                            required: true,
                            message: "请选择类型!"
                        }]
                    })(
                        <Select
                            size="large"
                            placeholder="检查点类型">
                            {allAddressTypeOptions}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='检查点地址'
                    {...formItemLayout}>
                    {getFieldDecorator("address", {
                        rules: [{
                            required: true,
                            message: '请输入检查点地址！',
                        }]
                    })(
                        <Input
                            size="large"
                            placeholder="请输入检查点地址"
                        />
                    )}
                </FormItem>
            </Form>
        )
    }
}
const AddAddressForm = Form.create()(addAddressForm);

class updateAddressForm extends Component {
    constructor(props) {
        super(props);

        this.state = {
            currentAddress: props.currentAddress,
            currentType: props.currentType,
            allAddressType: [{
                value: 1,
                text: '巡更'
            }, {
                value: 2,
                text: '巡检'
            }, {
                value: 3,
                text: '值周'
            }],
            confirmLoading: false,
        }
    }

    render() {
        const { getFieldDecorator } = this.props.form;

        const allAddressTypeOptions = this.state.allAddressType.map((d, index) =>
            <Option value={d.value} key={index}>{d.text}</Option>);

        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        };

        return (
            <Form>
                <FormItem
                    label='类型'
                    {...formItemLayout}>
                    {getFieldDecorator("type", {
                        initialValue: this.state.currentType,
                        rules: [{
                            required: true,
                            message: "请选择检查点类型!"
                        }]
                    })(
                        <Select
                            disabled
                            size="large"
                            placeholder="检查点类型">
                            {allAddressTypeOptions}
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='检查点地址'
                    {...formItemLayout}>
                    {getFieldDecorator("address", {
                        initialValue: this.state.currentAddress,
                        rules: [{
                            required: true,
                            message: '请输入检查点地址！',
                        }]
                    })(
                        <Input
                            size="large"
                            placeholder="请输入检查点地址"
                        />
                    )}
                </FormItem>
            </Form>
        )
    }
}
const UpdateAddressForm = Form.create()(updateAddressForm);




class AddressWithBlueteethManager extends Component {
    constructor(props) {
        super(props);

        this.state = {
            addMulVisible: false,
            addSingleVisible: false,
            updateSingleVisible: false,
            batchIncreaseVisible: false,
            alertVisible: false,
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            data: [],
            filteredInfo: null,
            sortedInfo: null,

            allAddressType: [{
                value: 1,
                text: '巡更'
            }, {
                value: 2,
                text: '巡检'
            }, {
                value: 3,
                text: '值周'
            }
            // , {
            //     value: 4,
            //     text: 'NFC巡检'
            // }, {
            //     value: 5,
            //     text: 'NFC值周'
            // }
        ],

        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        allAddressInBlueteethRelationApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    columnData.push({
                        key: index + 1,
                        address: item.address,
                        type: item.type,
                        number:item.macAddress
                    });
                });

                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                    batchIncreaseVisible: false
                });
                this.child.refreshData();
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    //点击表格中 添加 触发的操作
    showAddMulModal() {
        this.setState({
            addMulVisible: true,
            batchIncreaseVisible: false,
        });
    }
    //关联关系批量导入
    showBatchModal() {
        this.setState({
            batchIncreaseVisible: true,
        });
    }

    showAddSingleModal(address) {
        this.setState({
            addSingleVisible: true,
            currentAddress: address,
            batchIncreaseVisible: false,
        });
    }

    showUpdateSingleModal(address, type) {
        this.setState({
            updateSingleVisible: true,
            currentAddress: address,
            currentType: type,
            batchIncreaseVisible: false,
        });
    }

    handleDeleteMul(record) {
        deleteAddressWithBlueteethMulApi(record.address,
            parseInt(sessionStorage.getItem("departmentId")), record.type)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    //关闭模态框
    handleAddSingleCancel() {
        this.setState({
            alertVisible: false,
            addSingleVisible: false,
            batchIncreaseVisible: false,
        });
    }

    handleUpdateSingleCancel() {
        this.setState({
            alertVisible: false,
            updateSingleVisible: false,
            batchIncreaseVisible: false,
        });
    }

    //关闭模态框
    handleAddMulCancel() {
        this.setState({
            alertVisible: false,
            addMulVisible: false,
            batchIncreaseVisible: false,
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    onRef = (ref) => {
        this.child = ref
    }
    //子组件调用父组件方法刷新数据
    getAllData = (data) => {
        this.setState({
            columnData: data,
            batchIncreaseVisible: false,
        });
    }


    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        let columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key",
        }, {
            title: "检查点地址",
            dataIndex: "address",
            key: "address",
            sorter: (a, b) => {
                if (a.address < b.address) {
                    return -1;
                } else if (a.address > b.address) {
                    return 1;
                } else {
                    return 0;
                }
            },
            sortOrder: sortedInfo.columnKey === 'address' && sortedInfo.order,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.address.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title:"设备编号",
            dataIndex:"number",
            key:"number",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.number.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "类型",
            dataIndex: "type",
            key: "type",
            filters: this.state.allAddressType,
            filteredValue: filteredInfo.type || null,
            onFilter: (value, record) => record.type == value,
            filterIcon: filtered => <Icon type="filter" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            render: (text, record, index) => {
                if (record.type == 1) {
                    return (
                        <div>
                            <Tag color={'magenta'}>{'巡更'}</Tag>
                        </div>
                    )
                } else if (record.type == 2) {
                    return (
                        <div>
                            <Tag color={'blue'}>{'巡检'}</Tag>
                        </div>
                    )
                } else if (record.type == 3) {
                    return (
                        <div>
                            <Tag color={'green'}>{'值周'}</Tag>
                        </div>
                    )
                } 
                // else if (record.type == 4) {
                //     return (
                //         <div>
                //             <Tag color={'#E2C07F'}>{'NFC巡检'}</Tag>
                //         </div>
                //     )
                // }
                // else if (record.type == 5) {
                //     return (
                //         <div>
                //             <Tag color={'#E2C07F'}>{'NFC值周'}</Tag>
                //         </div>
                //     )
                // }
            },
        }, {
            title: "操作详情",
            key: "action",
            render: (text, record, index) => {
                if (record.type == 1) { // 巡更
                    return (
                        <span>
                            <a href="javascript:;" onClick={this.showUpdateSingleModal.bind(this,
                                record.address, record.type)}>更新关联</a>
                            <Divider type="vertical" />
                            <Popconfirm title="确定删除此地点的所有硬件设备巡更关联？" okText="确定" cancelText="取消"
                                onConfirm={() => this.handleDeleteMul(record)}>
                                <a href="#">全部删除</a>
                            </Popconfirm>
                        </span>
                    )
                } else if (record.type == 2) { //巡检
                    return (
                        <span>
                            <a href="javascript:;" onClick={this.showAddSingleModal.bind(this,
                                record.address)}>添加关联</a>
                            <Divider type="vertical" />
                            <Popconfirm title="确定删除此地点的所有硬件设备巡检关联？" okText="确定" cancelText="取消"
                                onConfirm={() => this.handleDeleteMul(record)}>
                                <a href="#">全部删除</a>
                            </Popconfirm>
                        </span>
                    )
                } else if (record.type == 3) { // 值周
                    return (
                        <span>
                            <a href="javascript:;" onClick={this.showUpdateSingleModal.bind(this,
                                record.address, record.type)}>更新关联</a>
                            <Divider type="vertical" />
                            <Popconfirm title="确定删除此地点的所有硬件设备值周关联？" okText="确定" cancelText="取消"
                                onConfirm={() => this.handleDeleteMul(record)}>
                                <a href="#">全部删除</a>
                            </Popconfirm>
                        </span>
                    )
                } else if (record.type == 4) { // NFC巡查
                    return (
                        <span>
                            {/* <a href="javascript:;" onClick={this.showUpdateSingleModal.bind(this,
                                record.address)}>更新关联</a> */}
                            {/* <Divider type="vertical" /> */}
                            <Popconfirm title="确定删除此地点的所有硬件设备值周关联？" okText="确定" cancelText="取消"
                                onConfirm={() => this.handleDeleteMul(record)}>
                                <a href="#">全部删除</a>
                            </Popconfirm>
                        </span>
                    )
                }
            },
        }];

        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" onClick={this.showAddMulModal.bind(this)} size="large">
                        <Icon type="plus" theme="outlined" />新增关联
                    </Button>
                    <Button type="primary" onClick={this.showBatchModal.bind(this)} size="large" style={{ marginLeft: 10 }}>
                        <Icon type="plus" theme="outlined" />批量导入
                    </Button>
                    <Button href={relationUploadTemplateUrl} style={{ marginLeft: 10 }}><Icon type="download" />下载模板</Button>
                    <Button style={{ marginLeft: '20px' }} onClick={this.clearAll}>清除筛选</Button>
                    <AddAddressWithBlueteethMulForm
                        visible={this.state.addMulVisible}
                        that={this} />
                    <AddAddressWithBlueteethSingleForForm
                        visible={this.state.addSingleVisible}
                        currentAddress={this.state.currentAddress}
                        that={this} />
                    <UpdateAddressWithBlueteethSingleForForm
                        visible={this.state.updateSingleVisible}
                        currentAddress={this.state.currentAddress}
                        currentType={this.state.currentType}
                        type={this.state.type}
                        that={this} />
                    <BatchIncreaseExport
                        visible={this.state.batchIncreaseVisible} getAllData={this.getAllData}
                    />
                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    expandedRowRender={(record) => {
                        return (
                            <AddressWithBlueteethInnerTable
                                onRef={this.onRef}
                                type={record.type}
                                address={record.address}
                                that={this} />)
                    }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        )
    }
}
//批量导入关联关系
class BatchIncreaseExport extends Component {
    constructor(props) {
        super(props)
        this.state = {
            visible: props.visible,
            fileList: [],
            uploading: false,
            isExport: false,
        }
    }
    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
        });
    }

    handleAddCancel() {
        console.log("----------------关闭")
        let columnData = [];
        allAddressInBlueteethRelationApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        address: item.address,
                        type: item.type,
                    });
                });

                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                });
                this.props.getAllData(columnData);
            })
        this.setState({
            visible: false,
            fileList: [],
            isExport: false,
            uploading: false,
            msg: ''
        });
    }
    handleUpload = () => {
        const { fileList } = this.state;
        const formData = new FormData();
        fileList.forEach(file => {
            formData.append('upfile', file);
        });
        formData.append('schoolId', sessionStorage.getItem("departmentId"))
        this.setState({
            uploading: true,
            msg: ''
        });
        batchIncreaseRelationApi(formData).then((res) => {
            //console.log("upload", res.data)
            if (res.data == "success") {
                this.setState({
                    uploading: false,
                    fileList: [],
                    isExport: true,
                    msg: "导入成功!"
                });
                message.success("导入成功!");
            } else if (res.data == "repeat_address") {
                this.setState({
                    uploading: false,
                    fileList: [],
                    isExport: true,
                    msg: "网点名称已存在,请重新导入!"
                });
                message.error("导入失败!");
            } else if (res.data == "repeat_blueTeeth") {
                this.setState({
                    uploading: false,
                    fileList: [],
                    isExport: true,
                    msg: "设备编号已存在,请重新导入!"
                });
                message.error("导入失败!");
            } else if (res.data == "repeat_blueTeethWithDifferentAddress") {
                console.log(1111)
                this.setState({
                    uploading: false,
                    fileList: [],
                    isExport: true,
                    msg: "同一类型的蓝牙设备无法关联不同检查点!"
                });
                message.warning("导入失败!");
            }else if (res.data == "fail") {
                this.setState({
                    uploading: false,
                    fileList: [],
                    isExport: true,
                    msg: "上传失败!"
                });
                message.warning("导入失败!");
            }
        })
    };

    render() {
        const { uploading, fileList } = this.state;
        const props = {
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: file => {
                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));
                return false;
            },
            fileList,
        };
        let drawerContent;
        let footerButton
        drawerContent = (
            <div style={{ textAlign: 'center' }}>
                <div style={{ color: 'gray' }}>
                    请选择需要导入的设备地址关联关系
                </div>
                <Upload {...props}>
                    <Button type="primary" style={{ marginTop: 15 }}>选择文件</Button>
                </Upload>
                <Button
                    type="primary"
                    onClick={this.handleUpload}
                    disabled={fileList.length === 0}
                    loading={uploading}
                    style={{ marginTop: 20 }}
                >
                    {uploading ? '正在导入' : '导入关联'}
                </Button>
                <div style={{ color: 'red', marginTop: 20, fontSize: 18 }}>
                    {this.state.isExport ? this.state.msg : ''}
                </div>
            </div>
        )
        footerButton = (
            <div>
                <Button size="large" onClick={this.handleAddCancel.bind(this)}
                    style={{ marginRight: 20 }}>关闭</Button>
            </div>
        )
        return (
            <Drawer
                bodyStyle={{ paddingBottom: 100, paddingRight: 50 }}
                width={500}
                title={'批量导入'}
                visible={this.state.visible}
                onClose={this.handleAddCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                {drawerContent}
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    {footerButton}
                </div>
            </Drawer>
        )
    }
}

class AddressWithBlueteethInnerTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            address: props.address,
            type: props.type,
            innerData: [],
            that: props.that
        };
    }

    componentDidMount() {
        this.refreshData();
        this.props.onRef(this);
    }

    componentWillReceiveProps(props) {
        // console.log('props', props)
        this.setState({
            address: props.address,
            that: props.that,
            type: props.type
        });
        this.refreshData();
    }

    refreshData() {

        console.log('AddressWithBlueteethInnerTable-refreshData', this.state.address, this.state.type);
        this.setState({
            tableLoading: true
        });
        const innerData = [];
        getAddressWithBlueteethByAddressApi(
            parseInt(sessionStorage.getItem("departmentId")), this.state.address, this.state.type)
            .then((res) => {
                res.data.forEach((item, index) => {
                    if (item.type != 4 && item.macAddress.length==16) {
                        let macAddressId = (item.macAddress.split(':'))[1].indexOf("00000") > -1 ? "无蓝牙模式" : (item.macAddress.split(':'))[1];
                        innerData.push({
                            macAddress: item.macAddress,
                            macAddressId: macAddressId,
                        })
                    } else {
                        let macAddressId = item.macAddress
                        innerData.push({
                            macAddress: item.macAddress,
                            macAddressId: macAddressId,
                        })
                    }

                })
                this.setState({
                    innerData: innerData,
                    tableLoading: false
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleDeleteSingle(address, macAddress) {
        deleteAddressWithBlueteethSingleApi(address, macAddress,
            parseInt(sessionStorage.getItem("departmentId")), this.state.type)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                    this.state.that.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    render() {
        let innerColumns = [{
            title: '设备编号',
            dataIndex: 'macAddressId',
            key: 'macAddressId',
            width: '70%',
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa' }} />,
            onFilter: (value, record) => record.macAddressId.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            },
        }, {
            title: "操作详情",
            key: "action",
            width: '30%',
            render: (text, record) => (
                <span>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDeleteSingle(this.state.address, record.macAddress)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];

        return (
            <Table
                columns={innerColumns}
                dataSource={this.state.innerData}
                pagination={false}
                size='small'
                loading={this.state.tableLoading}
                locale={{ emptyText: '暂无数据' }}
                bordered={true}
                rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
            />
        )
    }
}


class addAddressWithBlueteethMulForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            treeDisableed0: false,
            treeDisableed1: false,
            mockData: [], //穿梭框数据,表示地点数据
            targetKeys: [], //结果数据

            treeData: [], //用于多选蓝牙
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [], //结果数据
            selectedKeys: [], //以上为树结构的数据


            confirmLoading: false,
            alertVisible: false,
            msg: "", //提交失败时的提示语

            usableAddress: [], //这两个巡逻 一对一用
            usableZhiZhouAddress: [],
            usableMacAddress: [],
            usableMacAddressId: [],
            usedXgAddress: [],
            selectBlueteeth: '',
            visible: props.visible,
            that: props.that,
            currentStep: 0,
            currentType: 0,
        };
    }

    componentDidMount() {
        //this.refreshData();
    }

    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
            that: props.that,
        });
        //this.refreshData();
    }

    refreshData(type) {
        console.log('refreshData', type);
        this.setState({
            confirmLoading: true,
        });
        getUsableAddressAndMacAddressApi(type, parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                if (type == 1) { //巡更
                    let usableAddress = [];
                    let usableMacAddress = [];
                    let usableMacAddressId = [];

                    if (res.data.address.length != 0) {
                        res.data.address.forEach((item, index) => {
                            usableAddress.push({
                                address: item,
                            });
                        });
                    }
                    if (res.data.macAddress.length != 0) {
                        res.data.macAddress.forEach((item, index) => {
                            usableMacAddress.push({
                                macAddress: item.macAddress,
                                macAddressId: (item.macAddress.split(':'))[1],
                                // settleAddress: item.settleAddress,
                            });
                        });
                    }
                    this.setState({
                        usableAddress: usableAddress,
                        usableMacAddress: usableMacAddress,
                        usableMacAddressId: usableMacAddressId,
                        confirmLoading: false,
                    });

                } else if (type == 2) { //巡检
                    //地址穿梭框
                    let allAddress = [];
                    if (res.data.address.length != 0) {
                        res.data.address.forEach((item, index) => {
                            //console.log(item);
                            allAddress.push({
                                key: item,
                                title: item,
                                chose: 0
                            });
                        });
                    }
                    this.setState({
                        mockData: allAddress,
                    });

                    //蓝牙树
                    let treeData = [];
                    console.log(res.data.macAddress);
                    if (res.data.macAddress.length != 0) {
                        res.data.macAddress.forEach((item, index) => {
                            let treeLeaf = {
                                title: (item.macAddress.split(':'))[1],
                                key: item.macAddress,
                            }
                            treeData.push(treeLeaf);
                        });
                    } else {

                    }
                    console.log(treeData);
                    this.setState({
                        treeData: treeData,
                        checkedKeys: [],
                        expandedKeys: [],
                        autoExpandParent: true,
                        confirmLoading: false,
                    });
                } else if (type == 3) {
                    let usableZhiZhouAddress = [];
                    let usableMacAddress = [];
                    let usableMacAddressId = [];

                    if (res.data.address.length != 0) {
                        res.data.address.forEach((item, index) => {
                            usableZhiZhouAddress.push({
                                address: item,
                            });
                        });
                    }
                    if (res.data.macAddress.length != 0) {
                        res.data.macAddress.forEach((item, index) => {
                            usableMacAddress.push({
                                macAddress: item.macAddress,
                                macAddressId: (item.macAddress.split(':'))[1],
                                // settleAddress: item.settleAddress,
                            });
                        });
                    }
                    this.setState({
                        usableZhiZhouAddress: usableZhiZhouAddress,
                        usableMacAddress: usableMacAddress,
                        usableMacAddressId: usableMacAddressId,
                        confirmLoading: false,
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });


        getUsableAddressAndMacAddressForZhizhouApi(parseInt(sessionStorage.getItem("departmentId")), type)
            .then((res) => {


                this.setState({
                    usedXgAddress: res.data,
                    confirmLoading: false,
                });
            }
            )
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }

    onCheck = (checkedKeys) => {
        //console.log('onCheck', checkedKeys);
        console.log('onCheck', checkedKeys);
        if (checkedKeys[0] === ("35:00000:" + sessionStorage.getItem("departmentId"))) {
            this.setState({
                treeDisableed1: true,
                expandedKeys: [],
                checkedKeys
            })
        } else if (checkedKeys.length > 0) {
            this.setState({
                treeDisableed0: true,
                checkedKeys
            })
        } else if (checkedKeys.length == 0) {
            this.setState({
                treeDisableed0: false,
                treeDisableed1: false,
                checkedKeys
            })
        }
    }

    onSelect = (selectedKeys, info) => {
        //console.log('onSelect', info);
        //this.setState({ selectedKeys });
    }

    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })


    handleMockChange = (targetKeys) => {
        this.setState({ targetKeys });
    }

    mockReload = () => {
        this.setState({ targetKeys: [] });
    }

    renderFooter = () => (
        <Button
            size="small"
            style={{ float: 'right', margin: 5 }}
            onClick={this.mockReload}>重置</Button>
    )

    next = (e) => {
        //console.log('currentStep', this.state.currentStep);
        if (this.state.currentStep == 0) {
            this.setState({
                confirmLoading: true,
            });
            e.preventDefault();
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    console.log('currentType', values.type);
                    this.setState({
                        currentType: values.type,

                    });
                    this.refreshData(values.type);
                    const currentStep = this.state.currentStep + 1;
                    this.setState({ currentStep: currentStep, confirmLoading: false, });
                }
            });
        } else if (this.state.currentStep == 1) {
            if (this.state.currentType == 1) {
                e.preventDefault();
                this.props.form.validateFields((err, values) => {
                    if (!err) {
                        this.setState({
                            confirmLoading: true,
                        });
                        let addressArr = [values.address];
                        let macAddressArr = [values.macAddress];
                        addAddressWithBlueteethMulApi(addressArr, macAddressArr,
                            this.state.currentType, parseInt(sessionStorage.getItem("departmentId")))
                            .then((res) => {
                                if (res.data == "success") {
                                    message.success("添加成功!");
                                    this.setState({
                                        confirmLoading: false,
                                        alertVisible: false,
                                        treeDisableed0: false,
                                        treeDisableed1: false,
                                        checkedKeys: []
                                    });

                                    const currentStep = this.state.currentStep + 1;
                                    this.setState({ currentStep: currentStep });

                                    this.state.that.refreshData();
                                } else if (res.data == "fail") {
                                    this.setState({
                                        alertVisible: true,
                                        confirmLoading: false,
                                        msg: "修改失败,请检查信息或稍后再试!"
                                    });
                                }
                            })
                            .catch((e) => {
                                if (e.response) {
                                    //请求已发出，服务器返回状态码不是2xx。
                                    console.info(e.response.data)
                                    console.info(e.response.status)
                                    console.info(e.response.headers)
                                } else if (e.request) {
                                    // 请求已发出，但没有收到响应
                                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                                    // 在node中是一个http.ClientRequest实例
                                    console.info(e.request)
                                } else {
                                    //发送请求时异常，捕捉到错误
                                    console.info('error', e.message)
                                }
                                console.info(e.config)
                            });
                    }
                });
            } else if (this.state.currentType == 2) {
                if (this.state.targetKeys.length == 0) {
                    message.error("请选择地点!");
                } else {
                    const currentStep = this.state.currentStep + 1;
                    this.setState({ currentStep: currentStep });
                }
            }
            else if (this.state.currentType == 3) {
                e.preventDefault();

                console.log('值周提交');
                this.props.form.validateFields((err, values) => {
                    if (!err) {
                        this.setState({
                            confirmLoading: true,
                        });
                        let addressArr = [values.address];
                        let macAddressArr = [values.macAddress];
                        addAddressWithBlueteethMulApi(addressArr, macAddressArr,
                            this.state.currentType, parseInt(sessionStorage.getItem("departmentId")))
                            .then((res) => {
                                if (res.data == "success") {
                                    message.success("添加成功!");
                                    this.setState({
                                        confirmLoading: false,
                                        alertVisible: false,
                                        treeDisableed0: false,
                                        treeDisableed1: false,
                                        checkedKeys: []
                                    });
                                    console.log('值周提交111');
                                    const currentStep = this.state.currentStep + 1;
                                    this.setState({ currentStep: currentStep });

                                    this.state.that.refreshData();
                                } else if (res.data == "fail") {
                                    this.setState({
                                        alertVisible: true,
                                        confirmLoading: false,
                                        msg: "修改失败,请检查信息或稍后再试!"
                                    });
                                }
                            })
                            .catch((e) => {
                                if (e.response) {
                                    //请求已发出，服务器返回状态码不是2xx。
                                    console.info(e.response.data)
                                    console.info(e.response.status)
                                    console.info(e.response.headers)
                                } else if (e.request) {
                                    // 请求已发出，但没有收到响应
                                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                                    // 在node中是一个http.ClientRequest实例
                                    console.info(e.request)
                                } else {
                                    //发送请求时异常，捕捉到错误
                                    console.info('error', e.message)
                                }
                                console.info(e.config)
                            });
                    }
                });
            }
        } else if (this.state.currentStep == 2) {
            if (this.state.currentType == 2) {
                this.setState({
                    confirmLoading: true,
                });
                addAddressWithBlueteethMulApi(this.state.targetKeys, this.state.checkedKeys,
                    this.state.currentType, parseInt(sessionStorage.getItem("departmentId")))
                    .then((res) => {
                        if (res.data == "success") {
                            message.success("添加成功!");
                            this.setState({
                                confirmLoading: false,
                                alertVisible: false,
                            });

                            const currentStep = this.state.currentStep + 1;
                            this.setState({ currentStep: currentStep });

                            this.state.that.refreshData();
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }

        }
    }
    addZhizhou = (e) => {
        console.log(e);
        if (this.state.currentStep == 0) {
            this.setState({
                confirmLoading: true,
            });

            if (this.state.currentType == 3) {
                e.preventDefault();
                this.props.form.validateFields((err, values) => {
                    if (!err) {
                        console.log('currentType', values.type);
                        this.setState({
                            currentType: values.type,

                        });
                        this.refreshData(values.type);
                        const currentStep = this.state.currentStep + 1;
                        this.setState({ currentStep: currentStep, confirmLoading: false, });
                    }
                });
            }
        } else if (this.state.currentStep == 1) {



            e.preventDefault();

            console.log('值周提交');


            this.props.form.validateFields((err, values) => {
                console.log('values', values, err);


                console.log('selectBlueteeth', this.state.selectBlueteeth)
                if (!err) {
                    this.setState({
                        confirmLoading: true,
                    });
                    let addressArr = [values.address];
                    let address = values.macAddress ? values.macAddress : this.state.selectBlueteeth
                    let macAddressArr = [address];
                    addAddressWithBlueteethMulApi(addressArr, macAddressArr,
                        this.state.currentType, parseInt(sessionStorage.getItem("departmentId")))
                        .then((res) => {
                            if (res.data == "success") {
                                message.success("添加成功!");
                                this.setState({
                                    confirmLoading: false,
                                    alertVisible: false,
                                    treeDisableed0: false,
                                    treeDisableed1: false,
                                    checkedKeys: []
                                });
                                console.log('值周提交111');
                                const currentStep = this.state.currentStep + 1;
                                this.setState({ currentStep: currentStep });

                                this.state.that.refreshData();
                            } else if (res.data == "fail") {
                                this.setState({
                                    alertVisible: true,
                                    confirmLoading: false,
                                    msg: "修改失败,请检查信息或稍后再试!"
                                });
                            }
                        })
                        .catch((e) => {
                            if (e.response) {
                                //请求已发出，服务器返回状态码不是2xx。
                                console.info(e.response.data)
                                console.info(e.response.status)
                                console.info(e.response.headers)
                            } else if (e.request) {
                                // 请求已发出，但没有收到响应
                                // e.request 在浏览器里是一个XMLHttpRequest实例，
                                // 在node中是一个http.ClientRequest实例
                                console.info(e.request)
                            } else {
                                //发送请求时异常，捕捉到错误
                                console.info('error', e.message)
                            }
                            console.info(e.config)
                        });
                }
            });




        }


    }

    prev = () => {
        if (this.state.currentStep == 1) {
            this.setState({
                currentType: 0,
            });
        }
        const currentStep = this.state.currentStep - 1;
        this.setState({
            currentStep: currentStep,
        });
    }

    handleAddCancel = () => {
        //父类关闭
        this.state.that.handleAddMulCancel();

        this.props.form.resetFields();
        this.setState({
            currentStep: 0,
            currentType: 0,
            treeData: [], //用于多选蓝牙
            expandedKeys: [],
            checkedKeys: [],
            selectedKeys: [],

            targetKeys: [],
            mockData: [],

            usableAddress: [], //这两个巡逻 一对一用
            usableZhiZhouAddress: [],
            usableMacAddress: [],
            usableMacAddressId: [],
        });

    }

    render() {
        // console.log('step', this.state.currentStep);
        // console.log('type', this.state.currentType);
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };

        let stepPatrol = (
            <Steps
                current={this.state.currentStep}
                style={{
                    marginBottom: 30,
                }}>
                <Step title="选择添加 巡更/巡检/值周 关联" description="请选择并按下一步" />
                <Step title="选择检查点地址与设备编号" description="请选择并提交" />
                <Step title="完成" />
            </Steps>
        );

        let stepInspect = (
            <Steps
                current={this.state.currentStep}
                style={{
                    marginBottom: 30,
                }}>
                <Step title="选择添加 巡更/巡检/值周 关联" description="请选择并按下一步" />
                <Step title="选择检查点地址" description="可多选" />
                <Step title="选择设备编号" description="可多选" />
                <Step title="完成" />
            </Steps>
        );
        let stepDutyweek = (
            <Steps
                current={this.state.currentStep}
                style={{
                    marginBottom: 30,
                }}>
                <Step title="添加值周蓝牙与检查网点关联" description="请选择并按下一步" />

                <Step title="值周蓝牙与已有/新增网点关联" />
                <Step title="完成" />
            </Steps>
        );

        let drawerContent;
        if (this.state.currentStep == 0) {
            drawerContent = (
                <div>
                    <Steps
                        current={this.state.currentStep}
                        style={{
                            marginBottom: 30,
                        }}>
                        <Step title="选择添加 巡更/巡检 关联" description="请选择并按下一步" />
                    </Steps>
                    <Form onSubmit={this.next}>
                        <FormItem
                            label='关联类型'
                            {...formItemLayout}>
                            {getFieldDecorator("type", {
                                rules: [{
                                    required: true,
                                    message: "请选择添加关联类型!"
                                }]
                            })(
                                <Radio.Group
                                    size="large"
                                    buttonStyle="solid">
                                    <Radio.Button value={1}>巡更</Radio.Button>
                                    <Radio.Button value={2}>巡检</Radio.Button>
                                    <Radio.Button value={3}>值周</Radio.Button>
                                </Radio.Group>
                            )}
                        </FormItem>
                    </Form>
                </div>
            );
        } else if (this.state.currentStep == 1) {
            if (this.state.currentType == 1) {
                let addressOptions = this.state.usableAddress.map((d, index) =>
                    <Option value={d.address} key={index}>{d.address}</Option>);
                let macAddressOptions = this.state.usableMacAddress.map((d, index) =>
                    <Option value={d.macAddress} key={index}>{d.macAddress.split(':')[1]}</Option>);
                drawerContent = (

                    <div>
                        {stepPatrol}
                        <Form onSubmit={this.next}>
                            <FormItem
                                label='检查点'
                                {...formItemLayout}>
                                {getFieldDecorator("address", {
                                    rules: [{
                                        required: true,
                                        message: "请选择检查点地址!"
                                    }]
                                })(
                                    <Select
                                        size="large"
                                        placeholder="选择检查点地址">
                                        {addressOptions}
                                    </Select>
                                )}
                            </FormItem>
                            <FormItem
                                label='设备编号'
                                {...formItemLayout}>
                                {getFieldDecorator("macAddress", {
                                    rules: [{
                                        required: true,
                                        message: "请选择设备编号!"
                                    }]
                                })(
                                    <Select
                                        size="large"
                                        placeholder="选择设备编号">
                                        {macAddressOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Form>
                    </div>


                );
            } else if (this.state.currentType == 2) {
                drawerContent = (
                    <div>
                        {stepInspect}
                        <Transfer
                            style={{
                                marginTop: 30,
                                textAlign: 'center',
                            }}
                            dataSource={this.state.mockData}
                            showSearch
                            listStyle={{
                                width: 300,
                                height: 500,
                                textAlign: 'left',
                            }}
                            titles={['选项', '已选择']}
                            operations={['添加', '取消']}
                            targetKeys={this.state.targetKeys}
                            onChange={this.handleMockChange}
                            render={item => `${item.title}`}
                            footer={this.renderFooter}
                        />
                    </div>
                );
            } else if (this.state.currentType == 3) {
                let addressOptions = this.state.usableZhiZhouAddress.map((d, index) =>
                    <Option value={d.address} key={index}>{d.address}</Option>);
                let macAddressOptions = this.state.usableMacAddress.map((d, index) =>
                    <Option value={d.macAddress} key={index}>{d.macAddress.split(':')[1]}</Option>);
                let usedXgAddressOptions = this.state.usedXgAddress.map((d, index) =>
                    <Option value={d.address} key={d.macAddress}>{d.address}</Option>);

                drawerContent = (
                    <div>
                        {stepDutyweek}

                        <Tabs defaultActiveKey="1" >
                            <TabPane
                                tab={
                                    <span className="tab_span">
                                        选择已有检查点地址
                                    </span>
                                }
                                key="1"
                            >


                                <div style={{ marginTop: '40px' }}>
                                    <Form onSubmit={this.addZhizhou}>
                                        <FormItem
                                            label='检查点'
                                            {...formItemLayout}>
                                            {getFieldDecorator("address", {
                                                rules: [{
                                                    required: true,
                                                    message: "请选择检查点地址!"
                                                }]
                                            })(
                                                <Select
                                                    size="large"
                                                    onSelect={(value, key) => { console.log('select', key); this.setState({ selectBlueteeth: key.key }) }}
                                                    placeholder="选择检查点地址">
                                                    {usedXgAddressOptions}
                                                </Select>
                                            )}
                                        </FormItem>


                                    </Form>
                                </div>
                            </TabPane>
                            <TabPane
                                tab={
                                    <span className="tab_span">

                                        选择新增检查点地址
                                    </span>
                                }
                                key="2"
                            >
                                <div style={{ marginTop: '40px' }}>
                                    <Form onSubmit={this.addZhizhou}>
                                        <FormItem
                                            label='检查点'
                                            {...formItemLayout}>
                                            {getFieldDecorator("address", {
                                                rules: [{
                                                    required: true,
                                                    message: "请选择检查点地址!"
                                                }]
                                            })(
                                                <Select
                                                    size="large"
                                                    placeholder="选择检查点地址">
                                                    {addressOptions}
                                                </Select>
                                            )}
                                        </FormItem>
                                        <FormItem
                                            label='设备编号'
                                            {...formItemLayout}>
                                            {getFieldDecorator("macAddress", {
                                                rules: [{
                                                    required: false,
                                                    message: "请选择设备编号!"
                                                }]
                                            })(
                                                <Select
                                                    size="large"

                                                    placeholder="选择设备编号">
                                                    {macAddressOptions}
                                                </Select>
                                            )}
                                        </FormItem>

                                    </Form>
                                </div>

                            </TabPane>
                        </Tabs>

                    </div>
                );
            }
        } else if (this.state.currentStep == 2) {
            if (this.state.currentType == 1) {
                drawerContent = (
                    <div>
                        {stepPatrol}
                        <div style={{
                            textAlign: 'center',
                            width: '100%',
                            marginTop: 200,
                        }}>
                            <IconFont type='icon-locationiconsuccess' style={{ fontSize: '10em' }} />
                            <div style={{ fontSize: 20 }}>操作成功</div>
                        </div>
                    </div>
                )
            } else if (this.state.currentType == 2) {
                drawerContent = (
                    <div>
                        {stepInspect}

                        {this.state.treeData.length == 0 ?
                            (
                                <Tree
                                    checkable
                                    onExpand={this.onExpand}
                                    expandedKeys={this.state.expandedKeys}
                                    autoExpandParent={this.state.autoExpandParent}
                                    onCheck={this.onCheck}
                                    checkedKeys={this.state.checkedKeys}
                                    onSelect={this.onSelect}
                                    selectedKeys={this.state.selectedKeys}
                                >
                                    <TreeNode title="无蓝牙模式" key={"35:00000:" + sessionStorage.getItem("departmentId")} disabled={this.state.treeDisableed0} />

                                </Tree>
                            ) : (
                                <div>
                                    {/* <div style={{
                                        fontSize: 18,
                                        marginLeft: 24,
                                        marginBottom: 10,
                                    }}>设备编号</div> */}
                                    <Tree
                                        checkable
                                        onExpand={this.onExpand}
                                        expandedKeys={this.state.expandedKeys}
                                        autoExpandParent={this.state.autoExpandParent}
                                        onCheck={this.onCheck}
                                        checkedKeys={this.state.checkedKeys}
                                        onSelect={this.onSelect}
                                        selectedKeys={this.state.selectedKeys}
                                    >
                                        <TreeNode title="无蓝牙模式" key={"35:00000:" + sessionStorage.getItem("departmentId")} disabled={this.state.treeDisableed0} />
                                        <TreeNode title="蓝牙模式" key={1} disabled={this.state.treeDisableed1}>
                                            {this.renderTreeNodes(this.state.treeData)}
                                        </TreeNode>
                                    </Tree>
                                </div>
                            )
                        }
                    </div>
                )
            } else if (this.state.currentType == 3) {

                drawerContent = (
                    <div>
                        {stepDutyweek}
                        <div style={{
                            textAlign: 'center',
                            width: '100%',
                            marginTop: 200,
                        }}>
                            <IconFont type='icon-locationiconsuccess' style={{ fontSize: '10em' }} />
                            <div style={{ fontSize: 20 }}>操作成功</div>
                        </div>
                    </div>
                )
            }
        } else if (this.state.currentStep == 3) {
            if (this.state.currentType == 2) {
                drawerContent = (
                    <div>
                        {stepInspect}
                        <div style={{
                            textAlign: 'center',
                            width: '100%',
                            marginTop: 200,
                        }}>
                            <IconFont type='icon-locationiconsuccess' style={{ fontSize: '10em' }} />
                            <div style={{ fontSize: 20 }}>操作成功</div>
                        </div>
                    </div>
                )
            }
        }

        let footerButton;
        if (this.state.currentStep == 0) {
            footerButton = (
                <div>
                    <Button size="large" onClick={this.handleAddCancel.bind(this)}
                        style={{ marginRight: 20 }}>关闭</Button>
                    <Button type="primary" size="large" loading={this.state.confirmLoading}
                        onClick={this.next}>下一步</Button>
                </div>
            )
        } else if (this.state.currentStep == 1) {
            if (this.state.currentType == 1) {
                footerButton = (
                    <div>
                        <Button size="large" onClick={this.handleAddCancel.bind(this)}
                            style={{ marginRight: 20 }}>关闭</Button>
                        <Button type="primary" size="large" onClick={this.prev}
                            style={{ marginRight: 20 }} >上一步</Button>
                        <Button type="primary" size="large" loading={this.state.confirmLoading}
                            onClick={this.next}>提交</Button>
                    </div>
                )
            } else if (this.state.currentType == 2) {
                footerButton = (
                    <div>
                        <Button size="large" onClick={this.handleAddCancel.bind(this)}
                            style={{ marginRight: 20 }}>关闭</Button>
                        <Button type="primary" size="large" onClick={this.prev}
                            style={{ marginRight: 20 }} >上一步</Button>
                        <Button type="primary" size="large" loading={this.state.confirmLoading}
                            onClick={this.next}>下一步</Button>
                    </div>
                )
            } else if (this.state.currentType == 3) {
                footerButton = (
                    <div>
                        <Button size="large" onClick={this.handleAddCancel.bind(this)}
                            style={{ marginRight: 20 }}>关闭</Button>
                        <Button type="primary" size="large" onClick={this.prev}
                            style={{ marginRight: 20 }} >上一步</Button>
                        <Button type="primary" size="large" loading={this.state.confirmLoading}
                            onClick={this.addZhizhou}>提交</Button>
                    </div>
                )
            }
        } else if (this.state.currentStep == 2) {
            if (this.state.currentType == 1) {
                footerButton = (
                    <div>
                        <Button size="large" onClick={this.handleAddCancel.bind(this)}
                            style={{ marginRight: 20 }}>关闭</Button>
                    </div>
                )
            } else if (this.state.currentType == 2) {
                footerButton = (
                    <div>
                        <Button size="large" onClick={this.handleAddCancel.bind(this)}
                            style={{ marginRight: 20 }}>关闭</Button>
                        <Button type="primary" size="large" onClick={this.prev}
                            style={{ marginRight: 20 }} >上一步</Button>
                        <Button type="primary" size="large" loading={this.state.confirmLoading}
                            onClick={this.next}>提交</Button>
                    </div>
                )
            } else if (this.state.currentType == 3) {
                footerButton = (
                    <div>
                        <Button size="large" onClick={this.handleAddCancel.bind(this)}
                            style={{ marginRight: 20 }}>关闭</Button>
                    </div>
                )
            }
        } else if (this.state.currentStep == 3) {
            if (this.state.currentType == 2) {
                footerButton = (
                    <div>
                        <Button size="large" onClick={this.handleAddCancel.bind(this)}
                            style={{ marginRight: 20 }}>关闭</Button>
                    </div>
                )
            }
        }



        return (
            <Drawer
                bodyStyle={{ paddingBottom: 100, paddingRight: 50 }}
                width={800}
                title={'新增关联'}
                visible={this.state.visible}
                onClose={this.handleAddCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                <Skeleton loading={this.state.confirmLoading} active>
                    {drawerContent}
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Skeleton>
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    {footerButton}
                </div>
            </Drawer>
        )
    }
}
const AddAddressWithBlueteethMulForm = Form.create()(addAddressWithBlueteethMulForm);

class AddAddressWithBlueteethSingleForForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            treeData: [], //用于多选蓝牙
            treeDisableed0: false,
            treeDisableed1: false,
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [], //结果数据
            selectedKeys: [], //以上为树结构的数据

            confirmLoading: false,
            alertVisible: false,
            msg: "", //提交失败时的提示语


            visible: props.visible,
            that: props.that,
            currentAddress: props.currentAddress,
        }

    }

    componentDidMount() {
        //this.refreshData();
    }

    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
            that: props.that,
            currentAddress: props.currentAddress,
        });
        if (props.visible) {
            this.refreshData(props.currentAddress);
        }
    }

    refreshData(currentAddress) {
        this.setState({
            confirmLoading: true,
        });
        getBlueteethForRelationApi(currentAddress, 2,
            parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                //蓝牙树
                let treeData = [];
                if (res.data.length != 0) {
                    res.data.forEach((item, index) => {
                        let treeLeaf = {
                            title: item.macAddress.split(':')[1],
                            key: item.macAddress,
                        }
                        treeData.push(treeLeaf);
                    });
                }
                this.setState({
                    treeData: treeData,
                    checkedKeys: [],
                    expandedKeys: [],
                    autoExpandParent: true,
                    confirmLoading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    onExpand = (expandedKeys) => {
        if (this.state.treeDisableed1 == true) {
            this.setState({
                autoExpandParent: false,
            });
        } else {
            this.setState({
                expandedKeys,
                autoExpandParent: false,
            });
        }

    }

    onCheck = (checkedKeys) => {
        console.log('onCheck', checkedKeys);
        if (checkedKeys[0] === ("35:00000:" + sessionStorage.getItem("departmentId"))) {
            this.setState({
                treeDisableed1: true,
                expandedKeys: [],
                checkedKeys
            })
        } else if (checkedKeys.length > 0) {
            this.setState({
                treeDisableed0: true,
                checkedKeys
            })
        } else if (checkedKeys.length == 0) {
            this.setState({
                treeDisableed0: false,
                treeDisableed1: false,
                checkedKeys
            })
        }
    }

    onSelect = (selectedKeys, info) => {
        console.log('onSelect', info, selectedKeys);
        this.setState({ selectedKeys });
    }

    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} />;
    })


    handleAdd = () => {
        this.setState({
            confirmLoading: true,
        });
        addAndUpdateAddressWithBlueteethSingleApi(this.state.currentAddress,
            this.state.checkedKeys, 2, parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                if (res.data == "success") {
                    message.success("添加成功!");
                    this.setState({
                        confirmLoading: false,
                        alertVisible: false,
                        treeDisableed0: false,
                        treeDisableed1: false,
                        checkedKeys: []
                    });
                    this.handleAddCancel();
                    this.state.that.refreshData();
                } else if (res.data == "fail") {
                    this.setState({
                        alertVisible: true,
                        confirmLoading: false,
                        msg: "修改失败,请检查信息或稍后再试!"
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleAddCancel = () => {
        //父类关闭
        this.state.that.handleAddSingleCancel();

        this.setState({
            treeData: [], //用于多选蓝牙
            expandedKeys: [],
            checkedKeys: [],
            selectedKeys: [],
            alertVisible: false,
        });
    }

    render() {
        let drawerContent;
        let checkable = false;
        if (this.state.treeData.length == 0) {
            checkable = true
        }

        console.log(checkable)

        drawerContent = (
            <div>
                <Tree
                    checkable
                    onExpand={this.onExpand}
                    expandedKeys={this.state.expandedKeys}
                    autoExpandParent={this.state.autoExpandParent}
                    onCheck={this.onCheck}
                    checkedKeys={this.state.checkedKeys}
                    onSelect={this.onSelect}
                    selectedKeys={this.state.selectedKeys}
                >
                    <TreeNode title="无蓝牙模式" key={"35:00000:" + sessionStorage.getItem("departmentId")} disabled={this.state.treeDisableed0} />
                    <TreeNode title="蓝牙模式" key={1} disabled={this.state.treeDisableed1} disableCheckbox={checkable}>
                        {this.renderTreeNodes(this.state.treeData)}
                    </TreeNode>
                </Tree>
            </div>
        )

        let footerButton = (
            <div>
                <Button size="large" onClick={this.handleAddCancel.bind(this)}
                    style={{ marginRight: 20 }}>关闭</Button>
                <Button type="primary" size="large" loading={this.state.confirmLoading}
                    onClick={this.handleAdd}>提交</Button>
            </div>
        );
        return (
            <Drawer
                bodyStyle={{ paddingBottom: 100, paddingRight: 50 }}
                width={800}
                title={'为 ' + this.state.currentAddress + ' 添加关联'}
                visible={this.state.visible}
                onClose={this.handleAddCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                <Skeleton loading={this.state.confirmLoading} active>
                    {drawerContent}
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Skeleton>
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    {footerButton}
                </div>
            </Drawer>
        )
    }

}


class updateAddressWithBlueteethSingleForForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            usableMacAddress: [],

            currentMacAddress: null,

            confirmLoading: false,
            alertVisible: false,
            msg: "", //提交失败时的提示语

            visible: props.visible,
            that: props.that,
            currentAddress: props.currentAddress,
            currentType: props.currentType

        };
    }

    componentDidMount() {
        // this.refreshData();
    }

    componentWillReceiveProps(props) {
        console.log('props', props.currentAddress);
        if (props.visible && !this.state.visible) {
            this.refreshData(props.currentAddress, props.currentType);
        }
        this.setState({
            visible: props.visible,
            that: props.that,
            currentAddress: props.currentAddress,
            currentType: props.currentType
        });
    }

    refreshData(currentAddress, curretnType) {
        this.setState({
            confirmLoading: true,
        });
        getBlueteethForRelationApi(currentAddress, curretnType,
            parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                let usableMacAddress = [];
                if (res.data.length != 0) {
                    res.data.forEach((item, index) => {
                        usableMacAddress.push({
                            macAddress: item.macAddress,
                            // settleAddress: item.settleAddress,
                        });
                    });
                }
                this.setState({
                    currentMacAddress: usableMacAddress[0].macAddress,
                    usableMacAddress: usableMacAddress,
                    confirmLoading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    handleUpdate = (e) => {
        this.setState({
            confirmLoading: true,
        });
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                addAndUpdateAddressWithBlueteethSingleApi(this.state.currentAddress,
                    [values.macAddress], this.state.currentType, parseInt(sessionStorage.getItem("departmentId")))
                    .then((res) => {
                        if (res.data == "success") {
                            message.success("更新成功!");
                            this.setState({
                                confirmLoading: false,
                                alertVisible: false,
                            });
                            this.handleUpdateCancel();
                            this.state.that.refreshData();
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        });
    }

    handleUpdateCancel = () => {
        //父类关闭
        this.state.that.handleUpdateSingleCancel();

        this.props.form.resetFields();
        this.setState({
            usableMacAddress: [],
            currentAddress: null,
            currentMacAddress: null,
            alertVisible: false,
        });

    }

    render() {
        // console.log('step', this.state.currentStep);
        // console.log('type', this.state.currentType);
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };

        let macAddressOptions = this.state.usableMacAddress.map((d, index) =>
            <Option value={d.macAddress} key={index}>{d.macAddress.split(':')[1]}</Option>);

        let drawerContent = (
            <div>
                <Form onSubmit={this.handleUpdate}>
                    <FormItem
                        label='检查点地址'
                        {...formItemLayout}>
                        {getFieldDecorator("address", {
                            initialValue: this.state.currentAddress,
                            rules: [{
                                required: true,
                                message: "请选择检查点地址!"
                            }]
                        })(
                            <Input
                                size="large"
                                disabled={true}
                            ></Input>
                        )}
                    </FormItem>
                    <FormItem
                        label='设备编号'
                        {...formItemLayout}>
                        {getFieldDecorator("macAddress", {
                            initialValue: this.state.currentMacAddress,
                            rules: [{
                                required: true,
                                message: "请选择设备编号!"
                            }]
                        })(
                            <Select
                                size="large"
                                placeholder="选择设备编号">
                                {macAddressOptions}
                            </Select>
                        )}
                    </FormItem>
                </Form>
            </div>
        )

        let footerButton = (
            <div>
                <Button size="large" onClick={this.handleUpdateCancel.bind(this)}
                    style={{ marginRight: 20 }}>关闭</Button>
                <Button type="primary" size="large" loading={this.state.confirmLoading}
                    onClick={this.handleUpdate}>提交</Button>
            </div>
        )

        return (
            <Drawer
                bodyStyle={{ paddingBottom: 100, paddingRight: 50 }}
                width={800}
                title={'更新地点设备关联'}
                visible={this.state.visible}
                onClose={this.handleUpdateCancel.bind(this)}
                destroyOnClose={true}
                closable
            >
                <Skeleton loading={this.state.confirmLoading} active>
                    {drawerContent}
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Skeleton>
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    {footerButton}
                </div>
            </Drawer>
        )
    }
}
const UpdateAddressWithBlueteethSingleForForm = Form.create()(updateAddressWithBlueteethSingleForForm);


class SchoolMessagepushManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            addVisible: false,
            updateVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            currentId:undefined,
            data: [],
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        allMessagepushBySchoolApi(sessionStorage.getItem("departmentId"))
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        userId: item.userId,
                        realName: item.realName,
                        pushTime: item.pushTime,
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }
    updateHandleClick(id) {
        console.log("32", id);
            this.setState({
               currentId:id,
                updateVisible: true,
                alertVisible: false
            });
           
        }

    //点击表格中 添加班次 触发的操作
    showAddModal() {
        this.setState({
            addVisible: true,
        });
    }

    handleDelete(id) {
        deleteMessagepushApi(id)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleAddClick() {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addMessagepushFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                values.pushTime = moment(values.pushTime).format('HH:mm:ss');

                addMessagepushApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                addVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "exist") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "存在重复添加！"
                            });
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                addVisible: true,
                                confirmLoading: false,
                                msg: "添加失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                // }
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    handleAddCancel() {
        let val = this.refs.addMessagepushFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            addVisible: false
        });
    }
    handleUpdateCancel(){
        let val=this.updateZhizhouPushFormValue;
        
        this.setState({
            alertVisible:false,
            updateVisible:false
        });
        
    }
     //修改巡更推送时间
     updatePushTimeHandleClick = (id)=>{
        // console.log(1)
        this.setState({
            confirmLoading: true
        });
        let val=this.refs.updateZhizhouPushFormValue;
        console.log("res", this);
        val.validateFields((err, values) => {
            if(!err){
                values.pushTime=moment(values.pushTime).format('HH:mm:ss');
                // console.log("test", values.pushTime);
                // console.log("test2", id);
                updatePatrolPushTimeApi(id, values)
                .then((res)=>{
                    if(res.data=="success"){
                        console.log("success");
                        this.setState({
                            updateVisible:false,
                            confirmLoading:false,
                            
                        });
                        this.refreshData();
                        val.resetFields();
                    } else if(res.data=="fail"){
                        console.log('fail');
                            this.setState({
                                alertVisible: true,
                                updateVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
            }else {
                this.setState({
                    confirmLoading: false
                });
            }
            
        });
    }



    render() {
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "姓名",
            dataIndex: "realName",
            key: "realName"
        }, {
            title: "推送时间",
            dataIndex: "pushTime",
            key: "pushTime"
        }, {
            title: "操作详情",
            key: "action",
            render: (text, record) => (
                <span>
                    <a href="javascript:;" onClick={() => this.updateHandleClick(record.id)}>修改</a>
                        <Divider type="vertical" />
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDelete(record.id)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];

        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    {
                        this.state.addVisible ? (
                            <Modal
                                title={"新增推送对象"}
                                visible={this.state.addVisible}
                                onCancel={this.handleAddCancel.bind(this)}
                                closable
                                footer={[
                                    <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                        onClick={this.handleAddClick.bind(this)}>提交</Button>
                                ]}
                            >
                                <AddMessagepushForm ref="addMessagepushFormValue" />
                                {
                                    this.state.alertVisible ?
                                        (
                                            <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                        ) : null
                                }
                            </Modal>) : null
                    }
                    <Modal
                    title="修改巡更推送时间"
                    visible={this.state.updateVisible}
                    onCancel={this.handleUpdateCancel.bind(this)}
                    closable
                    footer={[
                        <Button key="submit" type="primary" size="large"
                        loading={this.state.confirmLoading}
                          onClick={this.updatePushTimeHandleClick.bind(this, this.state.currentId)}
                        >提交</Button>
                    ]}
                    >
                        <UpdateZhizhouTimeForm ref="updateZhizhouPushFormValue"/>
                        {
                            this.state.alertVisible ?
                                (
                                   <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                                }
                    </Modal>
                    <Button type="primary" onClick={this.showAddModal.bind(this)} size="large">
                        <Icon type="plus" theme="outlined" />新增推送对象
                    </Button>
                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                />
            </div>
        )
    }
}

//新增事件推送功能
class SchoolEventPushManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            addVisible: false,
            updateVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            currentId:undefined,
            data: [],
        }
    }

    componentDidMount() {
        this.refreshData();

    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        allEventpushBySchoolApi(sessionStorage.getItem("departmentId"))
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        userId: item.userId,
                        realName: item.realName,
                        type: item.type,
                        pushState: item.pushState
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }
//点击表格中 修改触发的操作
updateHandleClick(id) {
    console.log("32", id);
        this.setState({
           currentId:id,
            updateVisible: true,
            alertVisible: false
        });
       
    }
    //点击表格中 添加班次 触发的操作
    showAddModal() {
        this.setState({
            addVisible: true,
        });
    }
    //改变推送状态
    changePushState(event, record) {
        console.log("event", event)
        console.log("record", record)
        changeEventpushStateApi(event, record.id)
            .then((res) => {
                console.log(res.data)
            })
            .catch((e) => {
                console.info(e.config)
            });
    }
    //是否删除
    handleDelete(id) {
        deleteEventpushApi(id)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleAddClick() {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addEventpushFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                addEventpushApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                addVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "exist") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "此人在此时已有推送！"
                            });
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                addVisible: true,
                                confirmLoading: false,
                                msg: "添加失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                // }
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    handleAddCancel() {
        let val = this.refs.addEventpushFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            addVisible: false
        });
    }
    handleUpdateCancel(){
        let val=this.updateZhizhouPushFormValue;
        
        this.setState({
            alertVisible:false,
            updateVisible:false
        });
        
    }
    //修改事件推送时间 与修改值周推送时间共用接口
    updatePushTimeHandleClick = (id)=>{
        // console.log(1)
        this.setState({
            confirmLoading: true
        });
        let val=this.refs.updateZhizhouPushFormValue;
        console.log("res", this);
        val.validateFields((err, values) => {
            if(!err){
                values.pushTime=moment(values.pushTime).format('HH:mm:ss');
                // console.log("test", values.pushTime);
                // console.log("test2", id);
                updateZhizhouPushTimeApi(id, values)
                .then((res)=>{
                    if(res.data=="success"){
                        console.log("success");
                        this.setState({
                            updateVisible:false,
                            confirmLoading:false,
                            
                        });
                        this.refreshData();
                        val.resetFields();
                    } else if(res.data=="fail"){
                        console.log('fail');
                            this.setState({
                                alertVisible: true,
                                updateVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
            }else {
                this.setState({
                    confirmLoading: false
                });
            }
            
        });
    }

    render() {
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "姓名",
            dataIndex: "realName",
            key: "realName"
        }, {
            title: "推送类型",
            dataIndex: "type",
            key: "type"
        }, {
            title: "推送状态",
            key: "pushState",
            dataIndex: "pushState",
            //事件推送状态显示
            render: (text, record) => (
                <span>
                    <Switch
                        checkedChildren={<CheckOutlined />}
                        unCheckedChildren={<CloseOutlined />}
                        defaultChecked={this.state.columnData[record.key - 1].pushState == 1 ? true : false}
                        onClick={(e) => this.changePushState(e, record)}
                    />
                </span>
            )
        },
        {
            title: "操作详情",
            key: "action",
            render: (text, record) => (
                <span>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDelete(record.id)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];

        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    {
                        this.state.addVisible ? (
                            <Modal
                                title={"添加事件推送对象"}
                                visible={this.state.addVisible}
                                onCancel={this.handleAddCancel.bind(this)}
                                closable
                                footer={[
                                    <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                        onClick={this.handleAddClick.bind(this)}>提交</Button>
                                ]}
                            >
                                <AddEventpushForm ref="addEventpushFormValue" />
                                {
                                    this.state.alertVisible ?
                                        (
                                            <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                        ) : null
                                }
                            </Modal>) : null
                    }
                    <Modal
                    title="修改事件推送时间"
                    visible={this.state.updateVisible}
                    onCancel={this.handleUpdateCancel.bind(this)}
                    closable
                    footer={[
                        <Button key="submit" type="primary" size="large"
                        loading={this.state.confirmLoading}
                         onClick={this.updatePushTimeHandleClick.bind(this, this.state.currentId)}
                        >提交</Button>
                    ]}
                    >
                        <UpdateZhizhouTimeForm ref="updateZhizhouPushFormValue"/>
                        {
                            this.state.alertVisible ?
                                (
                                   <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                                }
                    </Modal>
                    <Button type="primary" onClick={this.showAddModal.bind(this)} size="large">
                        <Icon type="plus" theme="outlined" />新增推送对象
                    </Button>
                </div>
                <Table
                    columns={columns}
                    dataSource={this.state.columnData}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                />
            </div>
        )
    }
}

class SchoolKaoQinPushManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            addVisible: false,
            updateVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            currentId:undefined,
            data: [],
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        allKaoQinPushBySchoolApi(sessionStorage.getItem("departmentId"))
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        userId: item.userId,
                        realName: item.realName,
                        pushTime: item.pushTime,
                        pushState: item.pushState
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }
//点击表格中 修改触发的操作
updateHandleClick(id) {
    console.log("32", id);
        this.setState({
           currentId:id,
            updateVisible: true,
            alertVisible: false
        });
       
    }
    //点击表格中 添加班次 触发的操作
    showAddModal() {
        this.setState({
            addVisible: true,
        });
    }

    handleDelete(id) {
        deleteKaoQinPushApi(id)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }
    //改变推送状态
    changePushState(event, record) {
        console.log("event", event)
        console.log("record", record)
        changeEventpushStateApi(event, record.id)
            .then((res) => {
                console.log(res.data)
            })
            .catch((e) => {
                console.info(e.config)
            });
    }

    handleAddClick() {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addMessagepushFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                values.pushTime = moment(values.pushTime).format('HH:mm:ss');

                addKaoQinPushApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                addVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "exist") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "此人在此时已有推送！"
                            });
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                addVisible: true,
                                confirmLoading: false,
                                msg: "添加失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                // }
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    handleAddCancel() {
        let val = this.refs.addMessagepushFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            addVisible: false
        });
    }
    handleUpdateCancel(){
        let val=this.updateZhizhouPushFormValue;
        
        this.setState({
            alertVisible:false,
            updateVisible:false
        });
        
    }
    //修改考勤推送时间 与值周推送共用一个接口
    updatePushTimeHandleClick = (id)=>{
        // console.log(1)
        this.setState({
            confirmLoading: true
        });
        let val=this.refs.updateZhizhouPushFormValue;
        console.log("res", this);
        val.validateFields((err, values) => {
            if(!err){
                values.pushTime=moment(values.pushTime).format('HH:mm:ss');
                // console.log("test", values.pushTime);
                // console.log("test2", id);
                updateZhizhouPushTimeApi(id, values)
                .then((res)=>{
                    if(res.data=="success"){
                        console.log("success");
                        this.setState({
                            updateVisible:false,
                            confirmLoading:false,
                            
                        });
                        this.refreshData();
                        val.resetFields();
                    } else if(res.data=="fail"){
                        console.log('fail');
                            this.setState({
                                alertVisible: true,
                                updateVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
            }else {
                this.setState({
                    confirmLoading: false
                });
            }
            
        });
    }
    render() {
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "姓名",
            dataIndex: "realName",
            key: "realName"
        }, {
            title: "推送时间",
            dataIndex: "pushTime",
            key: "pushTime"
        }, {
            title: "推送状态",
            dataIndex: "pushState",
            key: "pushState",
            //考勤推送状态显示
            render: (text, record) => (
                <span>
                    <Switch
                        checkedChildren={<CheckOutlined />}
                        unCheckedChildren={<CloseOutlined />}
                        defaultChecked={this.state.columnData[record.key - 1].pushState == 1 ? true : false}
                        onClick={(e) => this.changePushState(e, record)}
                    />
                </span>
            )
        }, {
            title: "操作详情",
            key: "action",
            render: (text, record) => (
                <span>
                    <a href="javascript:;" onClick={() => this.updateHandleClick(record.id)}>修改</a>
                        <Divider type="vertical" />
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDelete(record.id)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];

        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    {
                        this.state.addVisible ? (
                            <Modal
                                title={"添加事件推送对象"}
                                visible={this.state.addVisible}
                                onCancel={this.handleAddCancel.bind(this)}
                                closable
                                footer={[
                                    <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                        onClick={this.handleAddClick.bind(this)}>提交</Button>
                                ]}
                            >
                                <AddMessagepushForm ref="addMessagepushFormValue" />
                                {
                                    this.state.alertVisible ?
                                        (
                                            <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                        ) : null
                                }
                            </Modal>) : null
                    }
                    <Modal
                    title="修改考勤推送时间"
                    visible={this.state.updateVisible}
                    onCancel={this.handleUpdateCancel.bind(this)}
                    closable
                    footer={[
                        <Button key="submit" type="primary" size="large"
                        loading={this.state.confirmLoading}
                         onClick={this.updatePushTimeHandleClick.bind(this, this.state.currentId)}
                        >提交</Button>
                    ]}
                    >
                        <UpdateZhizhouTimeForm ref="updateZhizhouPushFormValue"/>
                        {
                            this.state.alertVisible ?
                                (
                                   <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                                }
                    </Modal>
                    <Button type="primary" onClick={this.showAddModal.bind(this)} size="large">
                        <Icon type="plus" theme="outlined" />新增推送对象
                    </Button>
                </div>
                <Table
                    columns={columns}
                    dataSource={this.state.columnData}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                />
            </div>
        )
    }
}

class SchoolZhiZhouPushManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            addVisible: false,
            updateVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            currentId:undefined,
            data: [],
        }
    }

    componentDidMount() {
        this.refreshData();

    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        allZhiZhouPushBySchoolApi(sessionStorage.getItem("departmentId"))
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        userId: item.userId,
                        realName: item.realName,
                        pushTime: item.pushTime,
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }
    //点击表格中 修改触发的操作
    updateHandleClick(id) {
        console.log("32", id);
        this.setState({
            currentId:id,
            updateVisible: true,
            alertVisible: false
        });
    
    }
    //点击表格中 添加班次 触发的操作
    showAddModal() {
        this.setState({
            addVisible: true,
        });
    }

    handleDelete(id) {
        deleteZhiZhouPushApi(id)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleAddClick() {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addMessagepushFormValue;
        val.validateFields((err, values) => {
            console.log("test", values)
            if (!err) {
                values.pushTime = moment(values.pushTime).format('HH:mm:ss');

                addZhiZhouPushApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                addVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "exist") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "存在重复添加"
                            });
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                addVisible: true,
                                confirmLoading: false,
                                msg: "添加失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                // }
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    handleAddCancel() {
        let val = this.refs.addMessagepushFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            addVisible: false
        });
        console.log("test", val.resetFields())
    }

    handleUpdateCancel(){
        let val=this.updateZhizhouPushFormValue;
        
        this.setState({
            alertVisible:false,
            updateVisible:false
        });
        
    }
    //修改值周推送时间
    updatePushTimeHandleClick = (id)=>{
        // console.log(1)
        this.setState({
            confirmLoading: true
        });
        let val=this.refs.updateZhizhouPushFormValue;
        console.log("res", this);
        val.validateFields((err, values) => {
            if(!err){
                values.pushTime=moment(values.pushTime).format('HH:mm:ss');
                // console.log("test", values.pushTime);
                // console.log("test2", id);
                updateZhizhouPushTimeApi(id, values)
                .then((res)=>{
                    if(res.data=="success"){
                        console.log("success");
                        this.setState({
                            updateVisible:false,
                            confirmLoading:false,
                            
                        });
                        this.refreshData();
                        val.resetFields();
                    } else if(res.data=="fail"){
                        console.log('fail');
                            this.setState({
                                alertVisible: true,
                                updateVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
            }else {
                this.setState({
                    confirmLoading: false
                });
            }
            
        });
    }

    render() {
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "姓名",
            dataIndex: "realName",
            key: "realName"
        }, {
            title: "推送时间",
            dataIndex: "pushTime",
            key: "pushTime"
        }, {
            title: "操作详情",
            key: "action",
            render: (text, record) => (
                <span>
                    <a href="javascript:;" onClick={() => this.updateHandleClick(record.id)}>修改</a>
                        <Divider type="vertical" />
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDelete(record.id)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];

        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    {
                        this.state.addVisible ? (
                            <Modal
                                title={"添加事件推送对象"}
                                visible={this.state.addVisible}
                                onCancel={this.handleAddCancel.bind(this)}
                                closable
                                footer={[
                                    <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                        onClick={this.handleAddClick.bind(this)}>提交</Button>
                                ]}
                            >
                                <AddMessagepushForm ref="addMessagepushFormValue" />
                                {
                                    this.state.alertVisible ?
                                        (
                                            <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                        ) : null
                                }
                            </Modal>) : null
                    }
                    <Modal
                    title="修改值周推送时间"
                    visible={this.state.updateVisible}
                    onCancel={this.handleUpdateCancel.bind(this)}
                    closable
                    footer={[
                        <Button key="submit" type="primary" size="large"
                        loading={this.state.confirmLoading}
                         onClick={this.updatePushTimeHandleClick.bind(this, this.state.currentId)}
                        >提交</Button>
                    ]}
                    >
                        <UpdateZhizhouTimeForm ref="updateZhizhouPushFormValue"/>
                        {
                            this.state.alertVisible ?
                                (
                                   <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                                }
                    </Modal>
                  
                    <Button type="primary" onClick={this.showAddModal.bind(this)} size="large">
                        <Icon type="plus" theme="outlined" />新增推送对象
                    </Button>
                </div>
                <Table
                    columns={columns}
                    dataSource={this.state.columnData}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                />
            </div>
        )
    }
}
class updatezhizhouForm extends Component{
    constructor(props){
        super(props);
        this.state={
            test:[]
        };
    }
    componentDidMount(){

    }
    render(){
        const applyBeginHour = '01:00:00';
        const applyEndHour = '23:00:00';
        const disBeginHouse = () => {
            const hours = [];
            if (applyEndHour) {
              const timeArr = applyBeginHour.split(':');
              // eslint-disable-next-line no-plusplus
              for (let i = 0; i < 24; i++) {
                if (i <= timeArr[0]) {
                  hours.push(i);
                }
              }
            }
            return hours;
          };
          const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };
        return(
            <Form>
                <FormItem
                    label='推送时间'
                    {...formItemLayout}>
                    {getFieldDecorator("pushTime", {
                        initialValue: moment('08:00:00', 'HH:mm:ss'),
                        rules: [{ required: true, message: "请输入推送时间!" }]
                    })(
                        <TimePicker
                            size="large"
                            minuteStep={30}
                            secondStep={60}
                            disabledHours={disBeginHouse}
                            prefix={
                                <Icon type="clock-circle" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="推送时间"
                        />
                    )}
                </FormItem>
            </Form>
        )
    }
}
const UpdateZhizhouTimeForm = Form.create()(updatezhizhouForm);
class addEventpushForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolIdentityName: [],
            allPeople: [],
            treeValue: undefined,

        };
    }

    componentDidMount() {
        let allPeople = [];
        let schoolIdentityName = [];
        getAllPeopleBySchoolForMessagepush(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.identitys.forEach((item, index) => {
                    schoolIdentityName.push(item);
                });
                res.data.people.forEach((item, index) => {
                    allPeople.push({
                        userId: item.id,
                        realName: item.realName,
                        identityId: item.identity,
                        identityName: item.identityString
                    });
                });
                this.setState({
                    allPeople: allPeople,
                    schoolIdentityName: schoolIdentityName
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
        //-----上是用户类型，下是单位，学校用户的单位唯一
    }

    onChange = (value) => {
        this.setState({ treeValue: value });
    }

    disabledMinutes = (selectedHour) => {
        let result = [];
        for (let i = 1; i < 60; i++) {
            result.push(i);
        }
        return (result)
    }

    disabledSeconds = (selectedHour, selectedMinute) => {
        let result = [];
        for (let i = 1; i < 60; i++) {
            result.push(i);
        }
        return (result)
    }

    timepickerOnchange = (time) => {

    }

    render() {
        const { allPeople } = this.state;
        const { schoolIdentityName } = this.state;
        

        const treePeopleData = [];

        schoolIdentityName.forEach((item, index) => {
            treePeopleData.push({
                title: item,
                value: item,
                key: item,
                disabled: true,
                children: [],
            });
        });

        allPeople.forEach((item, index) => {
            let identityIndex = schoolIdentityName.indexOf(item.identityName);
            treePeopleData[identityIndex].children.push({
                title: item.realName,
                value: item.userId,
                key: item.userId,
            });
        });
        //console.log(treePeopleData);

        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };

        return (
            <Form>
                <FormItem
                    label='推送类型'
                    {...formItemLayout}>
                    {getFieldDecorator("type", {
                        rules: [{ required: true, message: "请选择推送类型!" }]
                    })(
                        <Select
                            allowClear={true}
                            style={{ width: '100%' }}
                            size="large"
                            placeholder="请选择推送类型">
                            <Option value={6}>区域入侵</Option>
                            <Option value={7}>重点人员识别</Option>
                            <Option value={8}>陌生人识别</Option>
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    label='推送对象'
                    {...formItemLayout}>
                    {getFieldDecorator("pushPeople", {
                        initialValue: [],
                        rules: [{
                            required: true,
                            message: "请选择推送对象!"
                        }]
                    })(
                        <TreeSelect
                            treeData={treePeopleData}
                            value={this.state.treeValue}
                            onChange={this.onChange}
                            multiple
                            treeNodeFilterProp='title'
                            treeDefaultExpandAll
                            placeholder="推送对象"
                            size="large"
                        />
                    )}
                </FormItem>
            </Form>
        );
    }
}
const AddEventpushForm = Form.create()(addEventpushForm);

class addMessagepushForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolIdentityName: [],
            allPeople: [],
            treeValue: undefined,

        };
    }

    componentDidMount() {
        let allPeople = [];
        let schoolIdentityName = [];
        getAllPeopleBySchoolForMessagepush(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.identitys.forEach((item, index) => {
                    schoolIdentityName.push(item);
                });
                res.data.people.forEach((item, index) => {
                    allPeople.push({
                        userId: item.id,
                        realName: item.realName,
                        identityId: item.identity,
                        identityName: item.identityString
                    });
                });
                this.setState({
                    allPeople: allPeople,
                    schoolIdentityName: schoolIdentityName
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
        //-----上是用户类型，下是单位，学校用户的单位唯一
    }

    onChange = (value) => {
        console.log(value);
        this.setState({ treeValue: value });
    }

    disabledMinutes = (selectedHour) => {
        let result = [];
        for (let i = 1; i < 60; i++) {
            result.push(i);
        }
        return (result)
    }

    disabledSeconds = (selectedHour, selectedMinute) => {
        let result = [];
        for (let i = 1; i < 60; i++) {
            result.push(i);
        }
        return (result)
    }

    timepickerOnchange = (time) => {

    }

    render() {
        const { allPeople } = this.state;
        const { schoolIdentityName } = this.state;
        const applyBeginHour = '01:00:00';
        const applyEndHour = '23:00:00';
        
        const availableallPeopleOptions = this.state.allPeople.map((d, index) =>
            <Option value={d.userId} key={index}>{d.realName}</Option>);
        const disBeginHouse = () => {
            const hours = [];
            if (applyEndHour) {
              const timeArr = applyBeginHour.split(':');
              // eslint-disable-next-line no-plusplus
              for (let i = 0; i < 24; i++) {
                if (i <= timeArr[0]) {
                  hours.push(i);
                }
              }
            }
            return hours;
          };

        const treePeopleData = [];

        schoolIdentityName.forEach((item, index) => {
            treePeopleData.push({
                title: item,
                value: item,
                key: item,
                disabled: true,
                children: [],
            });
        });

        allPeople.forEach((item, index) => {
            let identityIndex = schoolIdentityName.indexOf(item.identityName);
            treePeopleData[identityIndex].children.push({
                title: item.realName,
                value: item.userId,
                key: item.userId,
            });
        });
        //console.log(treePeopleData);

        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };

        return (
            <Form>
                <FormItem
                    label='推送时间'
                    {...formItemLayout}>
                    {getFieldDecorator("pushTime", {
                        initialValue: moment('08:00:00', 'HH:mm:ss'),
                        rules: [{ required: true, message: "请输入推送时间!" }]
                    })(
                        <TimePicker
                            size="large"
                            minuteStep={30}
                            secondStep={60}
                            disabledHours={disBeginHouse}
                            prefix={
                                <Icon type="clock-circle" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="推送时间"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='推送对象'
                    {...formItemLayout}>
                    {getFieldDecorator("pushPeople", {
                        initialValue: [],
                        rules: [{
                            required: true,
                            message: "请选择推送对象!"
                        }]
                    })(
                        // <TreeSelect
                        //     treeData={treePeopleData}
                        //     mode="multiple"
                        //     value={this.state.treeValue}
                        //     onChange={this.onChange}
                        //     placeholder="推送对象"
                        //     size="large"
                        // />
                        <Select
                            size="large"
                             mode="multiple"
                            placeholder="推送对象"
                            onChange={this.onChange}
                            showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) =>{
                            console.log(input, option)
                             return  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }}>
                            {availableallPeopleOptions}
                        </Select>
                    )}
                </FormItem>
               
            </Form>
        );
    }
}
const AddMessagepushForm = Form.create()(addMessagepushForm);



class SchoolInspectpushManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            addVisible: false,
            updateVisible: false,
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            currentId:undefined,
            data: [],
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        allInspectpushBySchoolApi(sessionStorage.getItem("departmentId"))
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        userId: item.userId,
                        realName: item.realName,
                        pushTime: item.pushTime,
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }
    //点击表格中 修改触发的操作
updateHandleClick(id) {
    console.log("32", id);
        this.setState({
           currentId:id,
            updateVisible: true,
            alertVisible: false
        });
       
    }

    //点击表格中 添加班次 触发的操作
    showAddModal() {
        this.setState({
            addVisible: true,
        });
    }
    //删除事件推送信息
    handleDelete(id) {
        deleteInspectpushApi(id)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //添加事件推送对象
    handleAddClick() {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addInspectpushFormValue;
        val.validateFields((err, values) => {
            console.log("test", values)
            if (!err) {
                values.pushTime = moment(values.pushTime).format('HH:mm:ss');

                addInspectpushApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                alertVisible: false,
                                addVisible: false,
                                confirmLoading: false
                            });
                            this.refreshData();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "exist") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "此人在此时已有推送！"
                            });
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                addVisible: true,
                                confirmLoading: false,
                                msg: "添加失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
                // }
            } else {
                this.setState({
                    confirmLoading: false
                });
            }
        });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    handleAddCancel() {
        let val = this.refs.addInspectpushFormValue;
        val.resetFields();
        this.setState({
            alertVisible: false,
            addVisible: false
        });
    }
    handleUpdateCancel(){
        let val=this.updateZhizhouPushFormValue;
        
        this.setState({
            alertVisible:false,
            updateVisible:false
        });
        
    }
    //修改巡检推送时间
    updatePushTimeHandleClick = (id)=>{
        // console.log(1)
        this.setState({
            confirmLoading: true
        });
        let val=this.refs.updateZhizhouPushFormValue;
        console.log("res", this);
        val.validateFields((err, values) => {
            if(!err){
                values.pushTime=moment(values.pushTime).format('HH:mm:ss');
                // console.log("test", values.pushTime);
                // console.log("test2", id);
                updateInspectPushTimeApi(id, values)
                .then((res)=>{
                    if(res.data=="success"){
                        console.log("success");
                        this.setState({
                            updateVisible:false,
                            confirmLoading:false,
                            
                        });
                        this.refreshData();
                        val.resetFields();
                    } else if(res.data=="fail"){
                        console.log('fail');
                            this.setState({
                                alertVisible: true,
                                updateVisible: true,
                                confirmLoading: false,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
            }else {
                this.setState({
                    confirmLoading: false
                });
            }
            
        });
    }

    render() {
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        }, {
            title: "姓名",
            dataIndex: "realName",
            key: "realName"
        }, {
            title: "推送时间",
            dataIndex: "pushTime",
            key: "pushTime"
        }, {
            title: "操作详情",
            key: "action",
            render: (text, record) => (
                <span>
                    <a href="javascript:;" onClick={() => this.updateHandleClick(record.id)}>修改</a>
                        <Divider type="vertical" />
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDelete(record.id)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];
         
        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    {
                        this.state.addVisible ? (
                            <Modal
                                title={"新增推送对象"}
                                visible={this.state.addVisible}
                                onCancel={this.handleAddCancel.bind(this)}
                                closable
                                footer={[
                                    <Button key="submit" type="primary" size="large" loading={this.state.confirmLoading}
                                        onClick={this.handleAddClick.bind(this)}>提交</Button>
                                ]}
                            >
                                <AddInspectpushForm ref="addInspectpushFormValue" />
                                {
                                    this.state.alertVisible ?
                                        (
                                            <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                        ) : null
                                }
                            </Modal>) : null
                    }
                    <Modal
                    title="修改巡检推送时间"
                    visible={this.state.updateVisible}
                    onCancel={this.handleUpdateCancel.bind(this)}
                    closable
                    footer={[
                        <Button key="submit" type="primary" size="large"
                        loading={this.state.confirmLoading}
                         onClick={this.updatePushTimeHandleClick.bind(this, this.state.currentId)}
                        >提交</Button>
                    ]}
                    >
                        <UpdateZhizhouTimeForm ref="updateZhizhouPushFormValue"/>
                        {
                            this.state.alertVisible ?
                                (
                                   <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                ) : null
                                }
                    </Modal>
                    <Button style={{ display: 'inline' }} type="primary" onClick={this.showAddModal.bind(this)} size="large">
                        <Icon type="plus" theme="outlined" />新增推送对象
                    </Button>
                    {/* <Alert style={{ display: 'inline', marginLeft: 20 }} message="巡检报告每周六推送" type="info" /> */}
                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={columns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                />
            </div>
        )
    }
}

class addInspectpushForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolIdentityName: [],
            allPeople: [],
            treeValue: undefined,

        };
    }

    componentDidMount() {
        let allPeople = [];
        let schoolIdentityName = [];
        getAllPeopleBySchoolForMessagepush(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.identitys.forEach((item, index) => {
                    schoolIdentityName.push(item);
                });
                res.data.people.forEach((item, index) => {
                    allPeople.push({
                        userId: item.id,
                        realName: item.realName,
                        identityId: item.identity,
                        identityName: item.identityString
                    });
                });
                this.setState({
                    allPeople: allPeople,
                    schoolIdentityName: schoolIdentityName
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
        //-----上是用户类型，下是单位，学校用户的单位唯一
    }

    onChange = (value) => {
        this.setState({ treeValue: value });
    }

    disabledMinutes = (selectedHour) => {
        let result = [];
        for (let i = 1; i < 60; i++) {
            result.push(i);
        }
        return (result)
    }

    disabledSeconds = (selectedHour, selectedMinute) => {
        let result = [];
        for (let i = 1; i < 60; i++) {
            result.push(i);
        }
        return (result)
    }

    timepickerOnchange = (time) => {

    }

   

    render() {
        const { allPeople } = this.state;
        const { schoolIdentityName } = this.state;

        const applyBeginHour = '01:00:00';
        const applyEndHour = '23:00:00';

        const disBeginHouse = () => {
            const hours = [];
            if (applyEndHour) {
              const timeArr = applyBeginHour.split(':');
              // eslint-disable-next-line no-plusplus
              for (let i = 0; i < 24; i++) {
                if (i <= timeArr[0]) {
                  hours.push(i);
                }
              }
            }
            return hours;
          };

        const treePeopleData = [];

        schoolIdentityName.forEach((item, index) => {
            treePeopleData.push({
                title: item,
                value: item,
                key: item,
                disabled: true,
                children: [],
            });
        });

        allPeople.forEach((item, index) => {
            let identityIndex = schoolIdentityName.indexOf(item.identityName);
            treePeopleData[identityIndex].children.push({
                title: item.realName,
                value: item.userId,
                key: item.userId,
            });
        });
        //console.log(treePeopleData);

        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };
        

        return (
            <Form>
                <FormItem
                    label='推送时间'
                    {...formItemLayout}>
                    {getFieldDecorator("pushTime", {
                        initialValue: moment('08:00:00', 'HH:mm:ss'),
                        rules: [{ required: true, message: "请输入推送时间!" }]
                    })(
                        <TimePicker
                            size="large"
                            minuteStep={30}
                            disabledHours={disBeginHouse}
                            // secondStep={60}
                            prefix={
                                <Icon type="clock-circle" style={{ color: "rgba(0,0,0,.25)" }} />
                            }
                            placeholder="推送时间"
                        />
                    )}
                </FormItem>
                <FormItem
                    label='推送对象'
                    {...formItemLayout}>
                    {getFieldDecorator("pushPeople", {
                        initialValue: [],
                        rules: [{
                            required: true,
                            message: "请选择推送对象!"
                        }]
                    })(
                        // <TreeSelect
                        //     treeData={treePeopleData}
                        //     value={this.state.treeValue}
                        //     onChange={this.onChange}
                        //     placeholder="推送对象"
                        //     size="large"
                        //     showSearch
                        //     mode="multiple"
                        //     optionFilterProp="children"
                        //     filterOption={(input, option) =>{
                        //         console.log(input, option)
                        //          return  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        //                 }}
                        // />
                        
                        <TreeSelect
                        treeData={treePeopleData}
                        showSearch
                        style={{ width: '100%' }}
                       
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="推送对象"
                        treeNodeFilterProp='title'
                        // optionFilterProp="children"
                        // filterTreeNode={(input, option) =>{
                        // console.log(input, option)
                        //  return  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        //         }}
                        treeDefaultExpandAll
                        onChange={this.onChange}
                        ></TreeSelect>
                    )}
                </FormItem>
            </Form>
        );
    }
}
const AddInspectpushForm = Form.create()(addInspectpushForm);

class schoolDistanceManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            nowDistance: 0,
            isUpdateOpen: false,
            alertVisible: false,
            msg: '',
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        getBlueteethApi(sessionStorage.getItem("departmentId"))
            .then((res) => {
                this.setState({
                    nowDistance: res.data.distance
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    handleUpdateDistanceSubmit = (e) => {
        e.preventDefault();
        if (!this.state.isUpdateOpen) {
            this.setState({
                isUpdateOpen: !this.state.isUpdateOpen,
            })
            this.props.form.validateFields((err, values) => {

            });
        } else {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    updateDistanceApi(sessionStorage.getItem("departmentId"), values)
                        .then((res) => {
                            if (res.data == "success") {
                                this.refreshData();
                                message.success("更新成功!");
                                this.setState({
                                    isUpdateOpen: !this.state.isUpdateOpen,
                                });
                            } else if (res.data == "fail") {
                                this.setState({
                                    alertVisible: true,
                                    msg: "修改失败,请检查信息或稍后再试!"
                                });
                            }
                        })
                }
            });
        }

    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div>
                <div style={{
                    fontSize: '20px',
                    color: 'rgba(0,0,0,.85)',
                    lineHeight: '28px',
                    fontWeight: 500,
                    marginBottom: '12px'
                }}>
                    <span>感应距离</span>
                </div>
                <Form
                    style={{
                        paddingTop: '14px',
                        paddingBottom: '14px'
                    }}
                    layout="inline"
                    onSubmit={this.handleUpdateDistanceSubmit}>
                    <FormItem>
                        {getFieldDecorator('distance', {
                            initialValue: this.state.nowDistance.toString(),
                            rules: [{
                                required: true
                            }],
                        })(
                            <Select
                                size='large'
                                style={{ 'width': '150px' }}
                                disabled={!this.state.isUpdateOpen}>
                                <Option value="1">非常近</Option>
                                <Option value="3">较近</Option>
                                <Option value="5">中等</Option>
                                <Option value="7">较远</Option>
                                <Option value="10">远</Option>
                            </Select>
                        )}
                    </FormItem>
                    <FormItem>
                        <Button
                            size='large'
                            type="primary"
                            htmlType="submit">
                            <Icon type={this.state.isUpdateOpen ? 'unlock' : 'lock'} />
                            {this.state.isUpdateOpen ? '保存' : '更新'}
                        </Button>
                    </FormItem>
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Form>
                <Alert
                    message="配置说明"
                    description={"当前感应距离为" + this.state.nowDistance + "米左右。由于受环境等因素影响，实际巡更时接设备信号的距离范围可能小于配置值。建议配置感应距离为中等。"}
                    type="info"
                    showIcon
                />
            </div>
        )
    }

}
const SchoolDistanceManager = Form.create()(schoolDistanceManager);

class SchoolBlueTeethManager extends Component {
    render() {
        return (
            <div>
                <Tabs
                    tabBarStyle={{
                        width: '180px'
                    }}
                    defaultActiveKey="1"
                    tabPosition="left">
                    <TabPane tab="感应距离" key="1">
                        <SchoolDistanceManager />
                    </TabPane>
                    <TabPane tab="UUID" key="2">
                        <SchoolUUIDManager />
                    </TabPane>
                    <TabPane tab="Major" key="3">
                        <SchoolMajorManager />
                    </TabPane>
                </Tabs>
            </div>
        );
    }
}

let keyNum = 0;
class schoolUUIDManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            uuidData: [],
            alertVisible: false,
            msg: '',
            canAdd: true
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        getBlueteethApi(sessionStorage.getItem("departmentId"))
            .then((res) => {
                //console.log(res);
                let uuid = res.data.uuid == null ? [] : res.data.uuid.split(',');
                let data = [];
                uuid.forEach((value, index) => {
                    data.push({
                        uuid: value,
                        key: keyNum++,
                        update: false
                    });
                });
                if (uuid.length >= 3) {
                    this.setState({
                        canAdd: false
                    });
                }
                keyNum--; //修正keyNum值
                this.setState({
                    uuidData: data
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不����2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出���但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例���
                    // 在node����是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    handleUpdateDistanceSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                updateUUIDApi(sessionStorage.getItem("departmentId"), values.names.filter(val => val !== "").join(","))
                    .then(res => {
                        if (res.data == "success") {
                            const { form } = this.props;
                            const keys = form.getFieldValue('keys');
                            keys.map(val => {
                                val.update = false;
                            });
                            form.setFieldsValue({
                                keys: keys
                            });
                            message.success("更新成功!");
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                msg: "修改失败,请检查信息或稍后再试!"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message);
                        }
                        console.info(e.config)
                    });
            }
        });

    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    remove = (k) => {
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        // We need at least one passenger
        if (keys.length === 1) {
            return;
        }

        // can use data-binding to set
        form.setFieldsValue({
            keys: keys.filter(val => val.key !== k),
        });
        if (keys.filter(val => val.key !== k).length < 3) {
            this.setState({
                canAdd: true
            });
        }
    }

    update = (k) => {
        const { form } = this.props;
        const keys = form.getFieldValue('keys');
        form.setFieldsValue({
            keys: keys.map(val => {
                if (val.key == k) {
                    val.update = !val.update;
                }
                return val;
            }),
        });
    }

    add = () => {
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        const nextKeys = keys.concat({
            uuid: "",
            key: ++keyNum,
            update: true
        });
        if (nextKeys.length >= 3) {
            this.setState({
                canAdd: false
            });
        }
        // can use data-binding to set
        // important! notify form to detect changes
        form.setFieldsValue({
            keys: nextKeys,
        });
    }

    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const formItemLayout = {
            wrapperCol: {
                xs: { span: 12 },
                sm: { span: 10 },
            },
        };
        getFieldDecorator('keys', { initialValue: this.state.uuidData });
        const keys = getFieldValue('keys');
        const formItems = keys.map((val, index) => (
            <FormItem
                {...formItemLayout}
                required={false}
                key={val.key}>
                {getFieldDecorator(`names[${val.key}]`, {
                    initialValue: val.uuid,
                    validateTrigger: ['onChange', 'onBlur'],
                    rules: [{
                        required: true,
                        whitespace: false,
                        message: "请输入UUID",
                        
                    }],
                })(
                    <Input
                        disabled={!val.update}
                        placeholder="请输入UUID"
                        style={{ width: '60%', marginRight: 8 }} />
                )}
                <Icon
                    className="dynamic-delete-button"
                    type={val.update ? 'unlock' : 'lock'}
                    onClick={() => this.update(val.key)} />
                {keys.length > 1 ? (
                    <Icon
                        style={{
                            marginLeft: '2px'
                        }}
                        className="dynamic-delete-button"
                        type="delete"
                        disabled={keys.length === 1}
                        onClick={() => this.remove(val.key)}
                    />
                ) : null}
            </FormItem>
        ));
        return (
            <div>
                <div style={{
                    fontSize: '20px',
                    color: 'rgba(0,0,0,.85)',
                    lineHeight: '28px',
                    fontWeight: 500,
                    marginBottom: '12px'
                }}>
                    <span>UUID</span>
                </div>
                <Form style={{
                    paddingTop: '14px',
                    paddingBottom: '14px'
                }}
                    onSubmit={this.handleUpdateDistanceSubmit}>
                    {formItems}
                    <FormItem {...formItemLayout}
                        className={this.state.canAdd ? null : 'hide'}>
                        <Button type="dashed" onClick={this.add} style={{ width: '60%' }}>
                            <Icon type="plus" /> 新增
                        </Button>
                    </FormItem>
                    <FormItem {...formItemLayout}>
                        <Button
                            style={{
                                width: '60%'
                            }}
                            size='large'
                            type="primary"
                            htmlType="submit">
                            保存
                        </Button>
                    </FormItem>
                    <Alert
                        message="配置说明"
                        description={"UUID硬件设备的通用识别码，用于识别硬件设备，请询问设备提供商获取UUID。新增、删除、修改后请务必点击保存以保存配置。"}
                        type="info"
                        showIcon
                        style={{
                            marginTop: "20px"
                        }}
                    />
                </Form>
            </div>
        )
    }
}
const SchoolUUIDManager = Form.create()(schoolUUIDManager);

class schoolMajorManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            major: 0,
            isUpdateOpen: false,
            alertVisible: false,
            msg: '',
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        getBlueteethApi(sessionStorage.getItem("departmentId"))
            .then((res) => {
                this.setState({
                    major: res.data.major
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    handleUpdateDistanceSubmit = (e) => {
        e.preventDefault();
        if (!this.state.isUpdateOpen) {
            this.setState({
                isUpdateOpen: !this.state.isUpdateOpen,
            })
        } else {
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    updateMajorApi(parseInt(sessionStorage.getItem("departmentId")), values.major)
                        .then((res) => {
                            if (res.data == "success") {
                                this.refreshData();
                                message.success("更新成功!");
                                this.setState({
                                    isUpdateOpen: !this.state.isUpdateOpen,
                                });
                            } else if (res.data == "fail") {
                                this.setState({
                                    alertVisible: true,
                                    msg: "修改失败,请检查信息或稍后再试!"
                                });
                            }
                        })
                        .catch((e) => {
                            if (e.response) {
                                //请求已发出，服务器返回状态码不是2xx。
                                console.info(e.response.data)
                                console.info(e.response.status)
                                console.info(e.response.headers)
                            } else if (e.request) {
                                // 请求已发出，但没有收到响应
                                // e.request 在浏览器里是一个XMLHttpRequest实例，
                                // 在node中是一个http.ClientRequest实例
                                console.info(e.request)
                            } else {
                                //发送请求时异常，捕捉到错误
                                console.info('error', e.message);
                            }
                            console.info(e.config)
                        });
                }
            });
        }

    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div>
                <div style={{
                    fontSize: '20px',
                    color: 'rgba(0,0,0,.85)',
                    lineHeight: '28px',
                    fontWeight: 500,
                    marginBottom: '12px'
                }}>
                    <span>Major</span>
                </div>
                <Form
                    style={{
                        paddingTop: '14px',
                        paddingBottom: '14px'
                    }}
                    layout="inline"
                    onSubmit={this.handleUpdateDistanceSubmit}>
                    <FormItem>
                        {getFieldDecorator('major', {
                            initialValue: this.state.major,
                            rules: [{
                                required: true,
                                message: "请输入正确的major值！",
                                pattern: new RegExp(/^[1-9]\d*$/, "g"),
                                getValueFromEvent: (event) => {
                                    return event.target.value.replace(/\D/g, '')
                                }
                            }],
                        })(
                            <Input
                                size="large"
                                style={{ 'width': '150px' }}
                                disabled={!this.state.isUpdateOpen}
                                value={this.state.major} />
                        )}
                    </FormItem>
                    <FormItem>
                        <Button
                            size='large'
                            type="primary"
                            htmlType="submit">
                            <Icon type={this.state.isUpdateOpen ? 'unlock' : 'lock'} />
                            {this.state.isUpdateOpen ? '保存' : '更新'}
                        </Button>
                    </FormItem>
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Form>
                <Alert
                    message="配置说明"
                    description={"Major硬件设备主ID，用于识别硬件设备，如需修改，请询问设备提供商获取major值。"}
                    type="info"
                    showIcon
                />
            </div>
        )
    }

}
const SchoolMajorManager = Form.create()(schoolMajorManager);

class SchoolEmergencyManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            emergencyContactData: [],
            emergencyContactOption: [],
            emergencyContactOptionData: [],
            tableLoading: false,
            cardLoading: false,
            page: 1,
            searchValue: ''
        }
    }

    componentDidMount() {
        this.setState({
            tableLoading: true,
            cardLoading: true
        })
        this.refreshData();
    }

    refreshData() {
        // 获取紧急联系人数据
        listEmergencyContactApi(sessionStorage.getItem("departmentId"))
            .then(res => {
                let emergencyContactData = [];
                res.data.forEach((v, i) => {
                    let row = {
                        userId: v.userId,
                        realname: v.realName,
                        phone: v.phone,
                        identity: v.identityString
                    };
                    emergencyContactData.push(row);
                });
                this.setState({
                    emergencyContactData: emergencyContactData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
        // 获取紧急联系人选项
        listEmergencyContactOptionApi(sessionStorage.getItem("departmentId"))
            .then(res => {
                let emergencyContactOption = [];
                res.data.forEach((v, i) => {
                    let row = {
                        userId: v.userId,
                        realname: v.realName,
                        phone: v.phone,
                        identity: v.identityString
                    };
                    emergencyContactOption.push(row);
                });
                this.setState({
                    page: 1,
                    emergencyContactOption: emergencyContactOption,
                    emergencyContactOptionData: emergencyContactOption,
                    searchValue: '',
                    cardLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    handleDelete = (userId) => {
        deleteEmergencyContactApi(sessionStorage.getItem("departmentId"), userId)
            .then(res => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error("删除失败,请稍后再试!")
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    handlePageChange = (page) => {
        this.setState({
            page: page
        })
    }

    handleSearch = (value) => {
        let reg = new RegExp(value);
        let rst = this.state.emergencyContactOptionData.filter(val => {
            if (reg.test(val.realname)) return val;
        })
        this.setState({
            page: 1,
            emergencyContactOption: rst
        });
    }

    handleShowAll = () => {
        this.setState({
            page: 1,
            emergencyContactOption: this.state.emergencyContactOptionData
        });
    }

    handleInsert = (userId) => {
        insertEmergencyContactApi(sessionStorage.getItem('departmentId'), userId)
            .then(res => {
                if (res.data == "success") {
                    message.success("设为紧急联系人成功!");
                    this.refreshData();
                } else {
                    message.error("设为紧急联系人失败,请稍后再试!")
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    handleSearchValueChange = (e) => {
        this.setState({
            searchValue: e.target.value
        });
    }

    render() {
        const columns = [{
            title: '序号',
            dataIndex: 'userId',
            key: 'userId',
            render: (text, record, index) => `${index + 1}`,
        }, {
            title: '姓名',
            dataIndex: 'realname',
            key: 'realname',
        }, {
            title: '用户类型',
            dataIndex: 'identity',
            key: 'identity',
        }, {
            title: '联系电话',
            dataIndex: 'phone',
            key: 'phone',
        }, {
            title: '操作详情',
            key: 'action',
            render: (text, record) => (
                <span>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDelete(record.userId)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            ),
        }];
        const option = this.state.emergencyContactOption.map((d, index) => {
            if (index < this.state.page * 5 && index >= this.state.page * 5 - 5) {
                return (
                    <Row style={{
                        marginTop: '5px'
                    }}>
                        <Card hoverable>
                            <Row type="flex" justify="space-between">
                                <Col span={20}>
                                    <div>
                                        <IconFont
                                            type="icon-xingmingyonghumingnicheng"
                                            style={{
                                                fontSize: '14px',
                                                marginRight: '5px'
                                            }} />
                                        {d.realname}
                                    </div>
                                    <div>
                                        <IconFont
                                            type="icon-zhiwei1"
                                            style={{
                                                fontSize: '14px',
                                                marginRight: '5px'
                                            }} />
                                        {d.identity}
                                    </div>
                                    <div>
                                        <IconFont
                                            type="icon-dianhua"
                                            style={{
                                                fontSize: '14px',
                                                marginRight: '5px'
                                            }} />
                                        {d.phone}
                                    </div>
                                </Col>
                                <Col span={4}>
                                    <Row type="flex" justify="end">
                                        <div
                                            style={{

                                            }}
                                            title='设为紧急联系人'
                                            onClick={() => { this.handleInsert(d.userId) }}
                                        >
                                            <IconFont
                                                type="icon-jiaru"
                                                style={{
                                                    color: '#000',
                                                    fontSize: '16px'
                                                }} />
                                        </div>
                                    </Row>
                                </Col>
                            </Row>
                        </Card>
                    </Row>
                )
            }
        });
        return (
            <div>
                <Row gutter={16}>
                    <Col span={18}>
                        <Card style={{ height: '775px' }}>
                            <Card.Meta title="紧急联系人" />
                            <Table
                                style={{ marginTop: '20px' }}
                                columns={columns}
                                dataSource={this.state.emergencyContactData}
                                loading={this.state.tableLoading}
                                locale={{ emptyText: '暂无数据' }}
                                rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                                pagination={{  //分页
                                    total: this.state.emergencyContactData.length, //数据总数量
                                    defaultPageSize: 10, //默认显示几条一页
                                    //pageSize: 10,
                                    showTotal: function (total) {  //设置显示一共几条数据
                                        return '共 ' + total + ' 条数据';
                                    },
                                    showSizeChanger: true,
                                    showQuickJumper: true,
                                    pageSizeOptions: [5, 10, 20, 30]
                                }}
                            />
                        </Card>
                    </Col>
                    <Col span={6}>
                        <Spin spinning={this.state.cardLoading}>
                            <Card style={{ height: '775px' }}>
                                <Row type="flex" justify="space-between">
                                    <Col span={12}>
                                        <Card.Meta title="可设置人员" />
                                    </Col>
                                    <Col span={12}>
                                        <Row type="flex" justify="end">
                                            <a
                                                style={{
                                                    verticalAlign: 'middle'
                                                }}
                                                onClick={() => { this.handleShowAll() }}>
                                                <IconFont
                                                    style={{
                                                        fontSize: '18px'
                                                    }}
                                                    type="icon-quanburenyuan"
                                                    className='icon' />
                                                <span style={{
                                                    marginLeft: '5px'
                                                }}>
                                                    显示全部
                                                </span>
                                            </a>
                                        </Row>
                                    </Col>
                                </Row>
                                <Row style={{
                                    marginTop: '20px',
                                    marginBottom: '20px'
                                }}>
                                    <Input.Search
                                        placeholder="请输入姓名查询"
                                        onSearch={value => this.handleSearch(value)}
                                        value={this.state.searchValue}
                                        onChange={(e) => { this.handleSearchValueChange(e) }}
                                        enterButton
                                    />
                                </Row>
                                {option}
                                <Row
                                    style={{
                                        marginTop: '20px',
                                    }}
                                    type="flex"
                                    justify="middle">
                                    <Pagination
                                        size="middle"
                                        current={this.state.page}
                                        defaultPageSize={5}
                                        showLessItems={true}
                                        hideOnSinglePage={true}
                                        total={this.state.emergencyContactOption.length}
                                        onChange={(page, pageSize) => { this.handlePageChange(page) }
                                        } />
                                </Row>
                            </Card>
                        </Spin>
                    </Col>
                </Row>
            </div>
        );
    }

}

class SchoolSafetyscenePushManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            safetyScenePushData: [],
            loading: false,
            allPeopleForChoose: []
        }
        this.columns = [{
            title: '序号',
            dataIndex: 'key',
            width: "25%"
        }, {
            title: '类别',
            dataIndex: 'category',
            width: "25%",
        }, {
            title: '负责人',
            dataIndex: 'realname',
            width: "50%",
            className: "safetyscenepush-realname-padding",
            editable: true,
            render: (text, record) => {
                if (text.length == 0) {
                    return (<span>点击此处设置负责人</span>);
                } else {
                    let people = text[0];
                    for (let i = 1; i < text.length; i++) {
                        people = people + '、' + text[i];
                    }
                    return people;
                }
            }
        }];
    }

    componentDidMount() {
        this.refreshData();
        // 获取所有绑定了微信服务号的本校用户
        this.getAllPeopleBySchoolForMessagepush();
    }

    getAllPeopleBySchoolForMessagepush() {
        getAllPeopleBySchoolForMessagepush(parseInt(sessionStorage.getItem("departmentId")))
            .then(res => {
                let allPeopleForChoose = [];
                res.data.people.forEach((item, index) => {
                    allPeopleForChoose.push({
                        userId: item.id,
                        realName: item.realName
                    });
                });
                this.setState({
                    allPeopleForChoose: allPeopleForChoose
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    refreshData() {
        this.setState({
            loading: true
        });
        // 获取所有大类及其负责人
        listSafetyScenePushApi(sessionStorage.getItem("departmentId"))
            .then(res => {
                let data = [];
                res.data.forEach((value, index) => {
                    let temp = {
                        key: index + 1,
                        id: value.id,
                        category: value.category,
                        realname: value.realName,
                        userId: value.userId,
                    }
                    data.push(temp);
                });
                this.setState({
                    safetyScenePushData: data
                });
                this.setState({
                    loading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    handleSave = (row) => {
        // console.log(row)
        if (row.realname !== undefined && row.realname.length > 0) {
            saveSafetyScenePushApi(parseInt(sessionStorage.getItem("departmentId")),
                row.id, row.realname)
                .then(res => {
                    if (res.data == "success") {
                        this.refreshData();
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message);
                    }
                    console.info(e.config)
                });
        }
    }

    render() {
        const { safetyScenePushData } = this.state;
        const components = {
            body: {
                row: EditableFormRow,
                cell: EditableCell,
            },
        };
        const columns = this.columns.map((col) => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    handleSave: this.handleSave,
                    allPeopleForChoose: this.state.allPeopleForChoose
                }),
            };
        });
        return (
            <div>
                <Table
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne editable-row" : "rowTwo editable-row"}
                    components={components}
                    dataSource={safetyScenePushData}
                    columns={columns}
                    loading={this.state.loading}
                    pagination={false}
                />
                <Alert
                    message="配置说明"
                    description="请确保负责人已绑定微信服务号，否则将无法成功配置。输入完毕后，请点击除输入框外的任意地方，以保存配置。"
                    type="info"
                />
            </div>
        );
    }
}

class SchoolManualManager extends Component {
    constructor(props) {
        super(props);

        this.state = {
            updateVisible: false, //控制新增用户模态框显示隐藏
            //addMyselfVisible: false,
            alertVisible: false,
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            outerData: [],
            categoryIdList: [],
            categoryNameList: [],
            categoryItemNum: [],
            currentcategoryId: 1,
            categoryKey: 1,
            // filteredInfo: null,
            // sortedInfo: null,

        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        getManualBySchoolAndCategoryApi(parseInt(sessionStorage.getItem("departmentId")), this.state.currentcategoryId)
            .then((res) => {
                res.data.data.forEach((value, i) => {
                    columnData.push({
                        key: i + 1,
                        item: value,
                    });
                });
                this.setState({
                    outerData: columnData,
                    tableLoading: false
                });

                getCategoryItemNumApi(
                    parseInt(sessionStorage.getItem("departmentId")), 0)
                    .then((res) => {
                        let categoryIdList = [];
                        let categoryNameList = [];
                        let categoryItemNum = [];
                        res.data.forEach((item, index) => {
                            categoryIdList.push(item.id);
                            categoryNameList.push(item.category);
                            categoryItemNum.push(item.num);
                        });
                        this.setState({
                            categoryIdList: categoryIdList,
                            categoryNameList: categoryNameList,
                            categoryItemNum: categoryItemNum,
                        });
                    }).catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

    }

    tabChange = (key) => {
        console.log(key + "key")
        this.setState({
            tableLoading: true,
            currentcategoryId: this.state.categoryIdList[key]
        });
        let columnData = [];
        getManualBySchoolAndCategoryApi(parseInt(sessionStorage.getItem("departmentId")), this.state.categoryIdList[key])
            .then((res) => {
                res.data.data.forEach((value, i) => {
                    columnData.push({
                        key: i + 1,
                        item: value,
                    });
                });
                this.setState({
                    outerData: columnData,
                    tableLoading: false,
                    categoryKey: this.state.categoryIdList[key]
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleDeleteByItem(item) {
        deleteManualByItemApi(parseInt(sessionStorage.getItem("departmentId")), item, 0)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                    this.state.that.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }


    showUpdateModal() {
        this.setState({
            updateVisible: true
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }

    //关闭更新信息模态框
    handleUpdateCancel() {
        this.setState({
            alertVisible: false,
            updateVisible: false
        });
        console.log('handleUpdateCancel');
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    onRef = (ref) => {
        this.child = ref
    }

    render() {
        const outerColumns = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            }, {
                title: "项目",
                dataIndex: "item",
                key: "item",
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.item.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            },
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                            onConfirm={() => this.handleDeleteByItem(record.item)}>
                            <a href="#">删除</a>
                        </Popconfirm>
                    </span>
                )
            }];
        console.log("this.state.categoryNameList", this.state.categoryNameList);
        const tabs = this.state.categoryNameList.map((d, index) =>
            <TabPane
                tab={
                    <div>{d}
                        <span style={{ float: 'right', lineHeight: 'initial' }}>
                            <Badge
                                count={this.state.categoryItemNum[index]}
                                style={{ backgroundColor: '#1890ff', }} />
                        </span>
                    </div>
                }
                key={index}>
                <Table
                    style={{ marginTop: '20px' }}
                    dataSource={this.state.outerData}
                    columns={outerColumns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    expandedRowRender={(record) => {
                        console.log("categoryKey", this.state.categoryKey)
                        return (
                            <ManualInnerTable
                                onRef={this.onRef}
                                item={record.item}
                                categoryKeyId={this.state.categoryKey}
                                that={this} />)
                    }}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        total: this.state.outerData.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }}
                />
            </TabPane>
        );


        return (
            <div>
                <div style={{ marginBottom: 16 }}>

                    <UpdateManualForm
                        visible={this.state.updateVisible}
                        currentcategoryId={this.state.currentcategoryId}
                        that={this} />


                </div>
                <Tabs
                    tabBarStyle={{
                        width: '180px'
                    }}
                    defaultActiveKey="0"
                    tabPosition="left"
                    onChange={this.tabChange}>
                    <Button type="primary" onClick={this.showUpdateModal.bind(this)} size="large">
                        <Icon type="usergroup-add" theme="outlined" />检查手册配置
                    </Button>
                    {tabs}

                </Tabs>
            </div>
        )
    }
}

class UpdateManualForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            treeData: [],
            confirmLoading: false,
            alertVisible: false,
            msg: "", //提交失败时的提示语
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],
            visible: props.visible,
            that: props.that,
            currentcategoryId: props.currentcategoryId
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    componentWillReceiveProps(props) {
        this.setState({
            visible: props.visible,
            that: props.that,
            currentcategoryId: props.currentcategoryId
        });
        this.refreshData();
    }

    refreshData() {
        this.setState({
            confirmLoading: true,
        })
        getManualForUpdateApi(parseInt(sessionStorage.getItem("departmentId")), 0, this.state.currentcategoryId)
            .then((res) => {

                console.log("treeData" + res.data);
                let treeData = [];
                let checkedKeys = [];
                res.data.forEach((value, index) => {
                    let selfDefinedExist = false;
                    let item = {
                        title: value.item,
                        key: value.item,
                        children: [],
                    }
                    value.contents.forEach((value2, index2) => {
                        item.children.push({
                            title: (value2.schoolId == 0 ? (<div>{value2.content}</div>) : (<div style={{ color: "#FF9966" }}>{value2.content}</div>)),
                            key: value.item + "-" + value2.content + "-" + value2.id,
                            schoolId: value2.schoolId,
                        });
                        if (value2.schoolId != 0) {
                            selfDefinedExist = true;
                        }
                        if (value2.used == 1) {
                            checkedKeys.push(value.item + "-" + value2.content + "-" + value2.id)
                        }
                        //console.log(value2.contents);
                    });
                    if (selfDefinedExist == true) {
                        item.title = (<div style={{ color: "#FF3300" }}>{value.item}</div>)
                    }
                    treeData.push(item);
                });
                //console.log('treeData', treeData);
                this.setState({
                    treeData: treeData,
                    confirmLoading: false,
                    checkedKeys: checkedKeys,
                    expandedKeys: checkedKeys
                });
                this.child.refreshData();
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //修改手册
    handleUpdateClick() {
        this.setState({
            confirmLoading: true
        });
        let values = [];
        this.state.checkedKeys.forEach((value, index) => {
            let temp = value.split('-');
            if (temp.length == 3) {
                values.push(value);
            }
        });
        updateManualApi(parseInt(sessionStorage.getItem("departmentId")), values, this.state.currentcategoryId)
            .then((res) => {
                if (res.data == "success") {
                    message.success("更新成功!");
                    this.setState({
                        confirmLoading: false
                    });
                    this.state.that.handleUpdateCancel();
                    this.state.that.refreshData();
                } else if (res.data == "fail") {
                    this.setState({
                        alertVisible: true,
                        confirmLoading: false,
                        msg: "修改失败,请检查信息或稍后再试!"
                    });
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    //关闭 alert 的提示
    handleClose() {
        this.setState({ alertVisible: false });
    }

    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }

    onCheck = (checkedKeys) => {
        //console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });
    }

    onSelect = (selectedKeys, info) => {
        //console.log('onSelect', info);
        //this.setState({ selectedKeys });
    }

    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            let color = { color: "#000000" };
            if (item.schoolId != undefined) {
                if (item.schoolId == 0) { color = { color: "#000000" } }
                else if (item.schoolId != 0) { color = { color: "#FF9966" } }
            }
            if (item)
                return (
                    <TreeNode title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
        }
        return <TreeNode {...item} />;
    })



    render() {
        //console.log('treeData', this.state.treeData);
        return (
            <Drawer
                bodyStyle={{ paddingBottom: 100, paddingRight: 50 }}
                width={800}
                title={'检查手册配置'}
                visible={this.state.visible}
                onClose={this.state.that.handleUpdateCancel.bind(this.state.that)}
                destroyOnClose={true}
                closable
            >
                <Skeleton loading={this.state.confirmLoading} active>
                    <Tree
                        checkable
                        onExpand={this.onExpand}
                        expandedKeys={this.state.expandedKeys}
                        autoExpandParent={this.state.autoExpandParent}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.checkedKeys}
                        onSelect={this.onSelect}
                        selectedKeys={this.state.selectedKeys}
                    >
                        {this.renderTreeNodes(this.state.treeData)}
                    </Tree>
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                            ) : null
                    }
                </Skeleton>
                <div
                    style={{
                        position: 'absolute',
                        left: 0,
                        bottom: 0,
                        width: '100%',
                        borderTop: '1px solid #e9e9e9',
                        padding: '10px 16px',
                        background: '#fff',
                        textAlign: 'right',
                    }}
                >
                    <Row type="flex" justify="space-around" align="middle">
                        <Col span={18}>

                            <Alert style={{ textAlign: "left" }} message="紫色代表该巡检项下有自定义内容，橘黄色代表是自定义内容" type="info" showIcon />
                        </Col>
                        <Col span={3}>
                            <Button size="large" onClick={this.state.that.handleUpdateCancel.bind(this.state.that)}>关闭</Button>
                        </Col>
                        <Col span={3}>
                            <Button type="primary" size="large" loading={this.state.confirmLoading}
                                onClick={this.handleUpdateClick.bind(this)}>保存</Button>
                        </Col>
                    </Row>

                </div>
            </Drawer>
        )
    }

}


class ManualInnerTable extends Component {
    constructor(props) {
        super(props);
        const innerColumns = [{
            title: '巡查项目',
            dataIndex: 'content',
            key: 'content',
            width: '90%',
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa' }} />,
            onFilter: (value, record) => record.content.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "操作详情",
            key: "action",
            width: '10%',
            render: (text, record) => (
                <span>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                        onConfirm={() => this.handleDeleteByContent(record.id, record.content)}>
                        <a href="#">删除</a>
                    </Popconfirm>
                </span>
            )
        }];
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            item: props.item,
            categoryId: props.categoryKeyId,
            innerData: [],
            innerColumns: innerColumns,
            that: props.that
        }
    }

    componentDidMount() {
        this.refreshData();
        this.props.onRef(this);
    }

    componentWillReceiveProps(props) {
        // console.log('props', props)
        this.setState({
            item: props.item,
            that: props.that,
        });
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        const innerData = [];
        getManualDetailBySchoolAndItemApi(
            parseInt(sessionStorage.getItem("departmentId")), this.state.item, this.state.categoryId)
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    innerData.push({
                        id: item.id,
                        content: item.content,
                    });
                });
                this.setState({
                    innerData: innerData,
                    tableLoading: false
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

    }

    handleDeleteByContent(manualId, content) {
        deleteManualByContentApi(manualId, content)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                    this.state.that.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        // this.setState({ searchText: selectedKeys[0] });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        // this.setState({ searchText: '' });
    }


    render() {
        return (
            <Table
                columns={this.state.innerColumns}
                dataSource={this.state.innerData}
                pagination={false}
                size='small'
                loading={this.state.tableLoading}
                locale={{ emptyText: '暂无数据' }}
                bordered={true}
                rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
            />
        )
    }
}

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

const AutoCompleteOption = AutoComplete.Option;
class EditableCell extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            editing: false
        };
    }
    componentDidMount() {
        if (this.props.editable) {
            document.addEventListener('click', this.handleClickOutside, true);
        }
    }

    componentWillUnmount() {
        if (this.props.editable) {
            document.removeEventListener('click', this.handleClickOutside, true);
        }
    }

    toggleEdit = () => {
        const editing = !this.state.editing;
        this.setState({ editing });
    }

    handleClickOutside = (e) => {
        const { editing } = this.state;
        // console.log('this.cell', this.cell.childNodes[0].childNodes[0]);
        let inputElement = this.cell.childNodes[0].childNodes[0];
        if (editing && inputElement !== e.target && !inputElement.contains(e.target) && e.target.className !== "ant-select-dropdown-menu-item ant-select-dropdown-menu-item-active") {
            this.save();
        }
    }

    save = () => {
        const { record, handleSave } = this.props;
        this.form.validateFields((error, values) => {
            if (error) {
                return;
            }
            this.toggleEdit();
            // console.log(values)
            handleSave({ ...record, ...values });
        });
    }

    render() {
        const { editing } = this.state;
        const {
            editable,
            dataIndex,
            title,
            record,
            index,
            handleSave,
            allPeopleForChoose,
            ...restProps
        } = this.props;
        const children = allPeopleForChoose === undefined ? [] : allPeopleForChoose.map((val, index) =>
            <Option value={val.userId} key={val.userId}>{val.realName}</Option>);

        // console.log(this.props)


        return (
            <td ref={node => (this.cell = node)} {...restProps}>
                {editable ? (
                    <EditableContext.Consumer>
                        {(form) => {
                            this.form = form;
                            return (
                                editing ? (
                                    <FormItem style={{ margin: 0, width: "200px" }}>
                                        {form.getFieldDecorator(dataIndex, {
                                            rules: [{
                                                required: false,
                                            }],
                                            initialValue: record.userId,
                                        })(
                                            <Select
                                                style={{ width: 200 }}
                                                placeholder="请输入负责人姓名"
                                                mode="multiple"
                                            >
                                                {children}
                                            </Select>
                                        )}
                                    </FormItem>
                                ) : (
                                    <div
                                        className="editable-cell-value-wrap"
                                        style={{
                                            paddingRight: 24,
                                            width: "200px"
                                        }}
                                        onClick={this.toggleEdit}
                                    >
                                        {
                                            restProps.children[2] == undefined ?
                                                (<span>点击此处设置负责人</span>) :
                                                restProps.children
                                        }
                                    </div>
                                )
                            );
                        }}
                    </EditableContext.Consumer>
                ) : restProps.children}
            </td>
        );
    }
}


class AttendanceSchedule extends Component {
    constructor(props) {
        super(props);
        this.state = {
            scheduleTag: [],
            scheduleTagDiy: [],
            scheduleData: {},
            tagLoading: true,
            dataLoading: true,

            addTagVisible: false,
            alertVisible: false,
            msg: '',
            confirmLoading: false,

            currentYear: parseInt(moment().format('YYYY')),
            currentMonth: parseInt(moment().format('MM')),
            tagColor: [
                '#52c41a', //一般双休日0
                '#faad14', //法定节假日1
                '#722ed1', //自定义2
                '#fa541c', //工作日3
            ],
        }
    }

    componentDidMount() {
        this.refreshTag();
        this.refreshData();
    }

    refreshTag() {
        this.setState({
            tagLoading: true
        });
        getScheduleTagApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                let scheduleTag = [];
                let scheduleTagDiy = [];
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    if (item.type == 2) {
                        scheduleTagDiy.push({
                            id: item.id,
                            type: item.type,
                            name: item.name,
                        })
                    } else {
                        scheduleTag.push({
                            id: item.id,
                            type: item.type,
                            name: item.name,
                        });
                    }
                });
                this.setState({
                    scheduleTag: scheduleTag,
                    scheduleTagDiy: scheduleTagDiy,
                    tagLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    refreshData() {
        this.setState({
            dataLoading: true
        });
        let { currentMonth } = this.state;
        getScheduleDataApi(parseInt(sessionStorage.getItem("departmentId")),
            this.state.currentYear, [currentMonth - 1, currentMonth, currentMonth + 1])
            .then((res) => {
                let scheduleData = {};
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    if (item.diyType == -1) {
                        scheduleData[item.date] = {
                            tagName: item.name,
                            type: item.type,
                            lunarday: item.lunarday
                        }
                    } else {
                        scheduleData[item.date] = {
                            tagName: item.diyName,
                            type: item.diyType,
                            lunarday: item.lunarday
                        }
                    }
                });
                this.setState({
                    scheduleData: scheduleData,
                    dataLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    addTagShowModal = () => {
        this.setState({ addTagVisible: true })
    }

    addTagHandleCancel = () => {
        this.setState({ addTagVisible: false })
    }

    addTagHandleClick = () => {
        this.setState({
            confirmLoading: true
        });
        let val = this.refs.addScheduleTagFormValue;
        val.validateFields((err, values) => {
            if (!err) {
                //console.log(values);
                addScheduleTagApi(parseInt(sessionStorage.getItem("departmentId")), values.scheduleTagName)
                    .then((res) => {
                        if (res.data == "success") {
                            this.setState({
                                addTagVisible: false,
                                confirmLoading: false
                            });
                            this.refreshTag();
                            message.success("添加成功!");
                            val.resetFields();
                        } else if (res.data == "exist") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "节日已存在！"
                            });
                        } else if (res.data == "fail") {
                            this.setState({
                                alertVisible: true,
                                confirmLoading: false,
                                msg: "添加失败！"
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            } else {
                this.setState({
                    alertVisible: true,
                    confirmLoading: false,
                    msg: "表单错误！"
                });
            }
        });
    }

    handleAlertClose = () => {
        this.setState({ alertVisible: false });
    }

    dateCellRender = (value) => {
        let { scheduleData } = this.state;
        let data = scheduleData[value.format('YYYY-MM-DD')];
        if (data == undefined) {
            return (
                <div
                    style={{ height: '100%', wordWrap: 'break-word', wordBreak: 'break-all' }}
                    onDrop={(e) => this.drop(e, value.format('YYYY-MM-DD'))}
                    onDragOver={(e) => this.dragOver(e)} >
                </div>
            );
        }

        let color = this.state.tagColor[data.type];
        return (
            <div
                style={{ height: '100%', wordWrap: 'break-word', wordBreak: 'break-all' }}
                onDrop={(e) => this.drop(e, value.format('YYYY-MM-DD'))}
                onDragOver={(e) => this.dragOver(e)}>
                <div style={{ float: 'right', fontSize: 12, color: '#00000066' }}>{data.lunarday}</div>
                <Badge style={{ width: '100%' }} color={color} text={data.tagName} />
            </div>
        );
    }

    onPanelChange = (value) => {
        // console.log(value);
        this.setState({
            currentYear: parseInt(value.format('YYYY')),
            currentMonth: parseInt(value.format('MM')),
        }, () => { this.refreshData(); })
    }

    // 拖拽开始
    dragStart = (e, item) => {
        console.log(item)
        e.dataTransfer.setData('id', item.id);// 拖拽元素携带的数据
        e.dataTransfer.setData('type', item.type);
    }
    // 拖拽元素经过放置元素时
    dragOver = (e) => {
        e.preventDefault();// 此处的代码是必须的  不然无法拖拽
    }
    // 拖拽元素放到放置元素时
    drop = (e, date) => {
        e.preventDefault();
        // 放置之后的后续操作
        let id = e.dataTransfer.getData('id');

        if (moment(date).isBefore(moment())) {
            message.error('日期已过，无法修改！')
        } else {
            updateScheduleTagApi(parseInt(sessionStorage.getItem("departmentId")), id, date)
                .then((res) => {
                    if (res.data == "success") {
                        message.success("修改日程成功!");
                        this.refreshData();
                    } else if (res.data == "fail") {
                        message.error("修改失败!");
                        this.refreshData();
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
        }
    }

    // 拖拽元素经过放置元素时
    deleteDragOver = (e) => {
        e.preventDefault();// 此处的代码是必须的  不然无法拖拽
    }
    // 拖拽元素放到放置元素时
    deleteDrop = (e) => {
        e.preventDefault();
        // 放置之后的后续操作
        let id = e.dataTransfer.getData('id');
        let type = e.dataTransfer.getData('type');

        if (type != 2) {
            message.error('默认节日不可删除！')
        } else {
            deleteScheduleTagApi(parseInt(sessionStorage.getItem("departmentId")), id)
                .then((res) => {
                    if (res.data == "success") {
                        message.success("删除成功!");
                        this.refreshTag();
                        this.refreshData();
                    } else if (res.data == "fail") {
                        message.error("删除失败!");
                        this.refreshTag();
                        this.refreshData();
                    }
                })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message)
                    }
                    console.info(e.config)
                });
        }
    }

    render() {
        let { scheduleTag, scheduleTagDiy } = this.state;

        let tagList;
        if (scheduleTag.length > 0) {
            tagList = scheduleTag.map((value, index) => {
                let color = this.state.tagColor[value.type];
                return (
                    <Col style={{ marginBottom: 12 }} span={12}>
                        <Tag
                            style={{
                                width: '100%',
                                height: 30,
                                paddingTop: 4,
                                fontSize: 16
                            }}
                            color={color}
                            draggable={true}
                            onDragStart={(e) => this.dragStart(e, value)}>
                            {value.name}
                        </Tag>
                    </Col>
                )
            })
        } else {
            tagList = <Empty />
        }

        let tagDiyList;
        if (scheduleTagDiy.length > 0) {
            tagDiyList = scheduleTagDiy.map((value, index) => {
                let color = this.state.tagColor[value.type];
                return (
                    <Col style={{ marginBottom: 12 }} span={12}>
                        <Tag
                            style={{
                                width: '100%',
                                height: 30,
                                paddingTop: 4,
                                fontSize: 16
                            }}
                            color={color}
                            draggable={true}
                            onDragStart={(e) => this.dragStart(e, value)}>
                            {value.name}
                        </Tag>
                    </Col>
                )
            })
        } else {
            tagDiyList = <Empty />
        }

        return (
            <div style={{ marginTop: -4 }}>
                <Row gutter="16">
                    <Col span={6} style={{ textAlign: 'center', padding: 0 }}>
                        <div
                            className='innerbox'
                            style={{
                                width: '100%',
                                height: 'auto',
                                maxHeight: 810,
                                overflowY: 'auto',
                                padding: '0 8px',
                                paddingBottom: 12
                            }}>
                            <Divider>默认</Divider>
                            <Spin spinning={this.state.tagLoading}>
                                <Row gutter={12}>
                                    {tagList}
                                </Row>
                            </Spin>
                            <Divider>自定义</Divider>
                            <Spin spinning={this.state.tagLoading}>
                                <Row gutter={12}>
                                    {tagDiyList}
                                </Row>
                            </Spin>
                            <Button
                                onClick={this.addTagShowModal}
                                style={{ width: '100%', marginTop: 8 }}
                                icon='plus'>
                                添加
                            </Button>
                            <Button
                                type="dashed"
                                onDrop={(e) => this.deleteDrop(e)}
                                onDragOver={(e) => this.deleteDragOver(e)}
                                icon="delete"
                                style={{
                                    width: '100%',
                                    height: 80,
                                    marginTop: 16,
                                    color: 'brown',
                                    textAlign: 'center',
                                    borderColor: '#ff4d4f',
                                    background: '#ff4d4f22'
                                }}>
                                拖动至此处删除
                            </Button>
                            <Alert
                                style={{ marginTop: 16, textAlign: 'left' }}
                                message={<div><Icon type="info-circle" style={{ color: '#1890ff', marginRight: 12 }} />注意事项</div>}
                                description={
                                    <div>
                                        <Badge color="#1890ff" text="将节日选项拖动至日历中，可更新考勤时间表" />
                                        <Badge color="#1890ff" text="将节日选项拖动至红色框内，可删除自定义节日" />
                                        <Badge color="#1890ff" text="默认节日不可删除" />
                                    </div>
                                }
                                type="info"
                            />
                        </div>
                    </Col>
                    <Col span={18}>
                        <Spin spinning={this.state.dataLoading}>
                            <Calendar
                                defaultValue={moment()}
                                headerRender={({ value, type, onChange, onTypeChange }) => {
                                    let start = 0;
                                    let end = 12;

                                    let current = value.clone();
                                    let localeData = value.localeData();
                                    let months = [];
                                    for (let i = start; i < end; i++) {
                                        current.month(i);
                                        months.push(localeData.monthsShort(current));
                                    }

                                    let monthOptions = [];
                                    for (let index = start; index < end; index++) {
                                        monthOptions.push(
                                            <Select.Option key={`${index}`}>{months[index]}</Select.Option>,
                                        );
                                    }
                                    let month = value.month();

                                    let year = value.year();
                                    let options = [];
                                    for (let i = 2019; i < moment().year() + 3; i += 1) {
                                        options.push(
                                            <Select.Option key={i} value={i}>{i}年</Select.Option>,
                                        );
                                    }
                                    return (
                                        <div style={{ padding: '16px 12px', float: 'right' }}>
                                            <Select
                                                style={{ marginRight: 12, width: 100 }}
                                                size="large"
                                                onChange={newYear => {
                                                    let now = value.clone().year(newYear);
                                                    onChange(now);
                                                }}
                                                value={year}
                                            >
                                                {options}
                                            </Select>
                                            <Select
                                                style={{ width: 80 }}
                                                size="large"
                                                value={String(month)}
                                                onChange={selectedMonth => {
                                                    let newValue = value.clone();
                                                    newValue.month(parseInt(selectedMonth, 10));
                                                    onChange(newValue);
                                                }}
                                            >
                                                {monthOptions}
                                            </Select>
                                        </div>
                                    );
                                }}

                                onPanelChange={this.onPanelChange}
                                dateCellRender={this.dateCellRender}
                            />
                        </Spin>
                    </Col>
                </Row>
                <Modal
                    destroyOnClose={true}
                    title="添加自定义节日"
                    visible={this.state.addTagVisible}
                    onCancel={this.addTagHandleCancel}
                    closable
                    footer={[
                        <Button key="submit" type="primary" size="large"
                            loading={this.state.confirmLoading}
                            onClick={this.addTagHandleClick}>提交</Button>
                    ]}
                >
                    <AddScheduleTagForm ref="addScheduleTagFormValue" />
                    {
                        this.state.alertVisible ?
                            (
                                <Alert message={this.state.msg} type="error" closable afterClose={this.handleAlertClose} />
                            ) : null
                    }
                </Modal>
            </div>
        )
    }
}

class addScheduleTagForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        };

        return (
            <Form>
                <FormItem
                    label='节日名称'
                    {...formItemLayout}>
                    {getFieldDecorator("scheduleTagName", {
                        //initialValue: this.state.currentAddress,
                        rules: [{
                            required: true,
                            message: '请输入节日名称',
                        }]
                    })(
                        <Input
                            size="large"
                            placeholder="请输入节日名称"
                        />
                    )}
                </FormItem>
            </Form>
        )
    }
}
const AddScheduleTagForm = Form.create()(addScheduleTagForm);

class attendanceRecord extends Component {
    constructor(props) {
        super(props);
        this.state = {

            tableLoading: true,
            tableData: [],
            chartAttendanceRecordSearchData: {},
            searchOptionLoading: true,
            nameArr: [],
            userNumberArr: [],
            employerArr: [],
            deviceNameArr: [],
            ipArr: [],
            isSearch: false,
            filteredInfo: null,
            sortedInfo: null,
            searchChartLoading: true,
            // searchText: '',
            searchValue: {},
            // searchChartLoading: false,

            // chartSearchData: {
            //     timestamp: [],
            //     time: []
            // },

            enterStatusArr: [{
                value: 'in',
                text: '入校'
            }, {
                value: 'out',
                text: '出校'
            }],

            userTypeArr: [{
                value: 1,
                text: '教师'
            }, {
                value: 2,
                text: '后勤人员'
            }, {
                value: 3,
                text: '学生'
            }],

            photoUrl: '',
            photoVisible: false
        }
    }

    componentDidMount() {
        this.refreshData({
            timePre: moment().format('YYYY-MM-DD'),
            timeAfter: moment().format('YYYY-MM-DD'),
        });
        this.refreshSearchOptionData();
    }

    refreshData(values) {
        this.setState({
            tableLoading: true,
            // searchChartLoading: true,
        });
        let tableData = [];
        getAttendanceRecordApi(parseInt(sessionStorage.getItem("departmentId")), values)//接口获取数据 参数从浏览器实时仓库取
            .then((res) => {
                res.data.forEach((item, index) => {
                    //console.log("getAllUser", item);
                    tableData.push({
                        key: index + 1,
                        name: item.name,
                        userNumber: item.userNumber,
                        userType: item.userType,
                        employer: item.employer,
                        enter: item.enter,
                        time: item.time,
                        deviceName: item.deviceName,
                        ip: item.ip,
                        photoUrl: item.photoUrl,
                    });//类似ajax对responsedata的处理
                });

                this.setState({
                    tableData: tableData,
                    tableLoading: false,
                    searchValue: values,
                    // searchChartLoading: false,
                    // isSearch: true
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

    }

    refreshSearchOptionData() {
        this.setState({
            searchOptionLoading: true
        });
        getAttendanceSearchOptionDataApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                this.setState({
                    nameArr: res.data.nameArr,
                    userNumberArr: res.data.userNumberArr,
                    employerArr: res.data.employerArr,
                    deviceNameArr: res.data.deviceNameArr,
                    ipArr: res.data.ipArr,
                    searchOptionLoading: false,
                })
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    searchSubmit = (e) => {
        console.log("..................32");
        e.preventDefault();
        //antd表单提供的参数校验
        this.props.form.validateFields((err, values) => {
            values.name = values.name || undefined;
            values.userNumber = values.userNumber || undefined;
            values.employer = values.employer || undefined;
            values.enter = values.enter || undefined;
            values.ip = values.ip || undefined;
            values.userType = values.userType || undefined;

            console.log('Received values of form: ', values);
            if (values.name == undefined && values.userNumber == undefined && values.employer == undefined
                && (values.deviceName == undefined || values.deviceName.length == 0)
                && values.enter == undefined && values.timeArr == undefined && values.ip == undefined
                && values.userType == undefined) {
                message.error('请至少填写一项条件再进行搜索');
            } else {
                if (values.timeArr != undefined) {
                    values.timePre = values.timeArr[0].format('YYYY-MM-DD');
                    values.timeAfter = values.timeArr[1].format('YYYY-MM-DD');
                }

                if (values.deviceName != undefined && values.deviceName.length == 0) {
                    values.deviceName = undefined;
                }

                getAttendanceSearchChartDataApi(parseInt(sessionStorage.getItem("departmentId")), values)
                    .then(res => {
                        let chartAttendanceRecordSearchData = {
                            date: [],
                            studentInTimes: [],
                            studentOutTimes: [],
                            otherRoleOutTimes: [],
                            otherRoleInTimes: [],
                        };
                        // let chartAttendanceRecordSearchData = []
                        res.data.forEach((item, index) => {
                            console.log("输出表格数据");
                            console.log(item.date);
                            console.log(item.studentInTimes);
                            console.log(item.studentOutTimes);
                            console.log(item.otherRoleOutTimes);
                            console.log(item.otherRoleInTimes);
                            chartAttendanceRecordSearchData.date.push(item.date);
                            chartAttendanceRecordSearchData.studentInTimes.push(item.studentInTimes);
                            chartAttendanceRecordSearchData.studentOutTimes.push(item.studentOutTimes);
                            chartAttendanceRecordSearchData.otherRoleOutTimes.push(item.otherRoleOutTimes);
                            chartAttendanceRecordSearchData.otherRoleInTimes.push(item.otherRoleInTimes);
                            // chartAttendanceRecordSearchData.push({
                            //     date : item.date ,
                            //     studentInTimes : item.studentInTimes ,
                            //     studentOutTimes : item.studentOutTimes ,
                            //     otherRoleOutTimes : item.otherRoleOutTimes ,
                            //     otherRoleInTimes : item.otherRoleInTimes
                            // })
                        });
                        console.log("chartAttendanceRecordSearchData", chartAttendanceRecordSearchData)
                        this.setState({
                            isSearch: true,
                            searchChartLoading: false,
                            chartAttendanceRecordSearchData: chartAttendanceRecordSearchData,
                            alertVisible: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });

                this.refreshData({
                    name: values.name,
                    userNumber: values.userNumber,
                    employer: values.employer,
                    enter: values.enter,
                    timePre: values.timePre,
                    timeAfter: values.timeAfter,
                    deviceName: values.deviceName != undefined && values.deviceName.length > 0 ?
                        values.deviceName : undefined,
                    ip: values.ip,
                    userType: values.userType
                });


            }
        });
    }

    searchReset = () => {
        this.props.form.resetFields();
        this.setState({
            isSearch: false,
        })
        this.refreshData({
            timePre: moment().format('YYYY-MM-DD'),
            timeAfter: moment().format('YYYY-MM-DD'),
        });
    }

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    }

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    // handleSearch = (selectedKeys, confirm) => () => {
    //     confirm();
    //     this.setState({
    //         searchText: selectedKeys[0],
    //     });
    // }

    // handleSearchReset = clearFilters => () => {
    //     clearFilters();
    //     this.setState({
    //         searchText: '',
    //     });
    // }

    // setFullScreen(opts) {
    //     this.setState({
    //         fullScreenVisible: true,
    //     })
    //     let fullchart = echarts.init(document.getElementById('fullScreen'))
    //     fullchart.setOption(opts);
    // }

    // fullScreenCancel() {
    //     this.setState({
    //         fullScreenVisible: false,
    //     })
    // }

    //downloadAttendanceSearchResult
    outputSearchResult = () => {
        let { searchValue } = this.state;
        searchValue['department'] = sessionStorage.getItem("departmentId");

        let url = baseUrl + 'report/faceRecordExport?data=' + encodeURI(JSON.stringify(searchValue));

        // console.log(JSON.stringify(searchValue))
        console.log(encodeURI(url))
        window.open(encodeURI(url));
    }

    showPhoto = (url) => {
        this.setState({
            photoUrl: url,
            photoVisible: true
        })
    }

    cancelPhoto = () => {
        this.setState({
            photoUrl: '',
            photoVisible: false
        })
    }


    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;

        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key",
        }, {
            title: "姓名-编号",
            dataIndex: "name",
            key: "name",
            sorter: (a, b) => {
                if (a.name + a.userNumber < b.name + b.userNumber) {
                    return -1;
                } else {
                    return 1;
                }
            },
            sortOrder: sortedInfo.columnKey === 'name' && sortedInfo.order,
            render: (text, record) => {
                return text + '-' + record.userNumber;
            },
            // }, {
            //     title: "人员编号",
            //     dataIndex: "userNumber",
            //     key: "userNumber",
            //     sorter: (a, b) => {
            //         if (a.userNumber < b.userNumber) {
            //             return -1;
            //         } else if (a.userNumber > b.userNumber) {
            //             return 1;
            //         } else {
            //             return 0;
            //         }
            //     },
            //     sortOrder: sortedInfo.columnKey === 'userNumber' && sortedInfo.order,
        }, {
            title: '人员类别',
            dataIndex: 'userType',
            key: 'userType',
            render: (text, record) => {
                if (text == 1) {
                    return '教师'
                } else if (text == 2) {
                    return '后勤人员'
                } else if (text == 3) {
                    return '学生'
                }
            },
        }, {
            title: "部门",
            dataIndex: "employer",
            key: "employer",
            sorter: (a, b) => {
                if (a.userNumber < b.userNumber) {
                    return -1;
                } else if (a.userNumber > b.userNumber) {
                    return 1;
                } else {
                    return 0;
                }
            },
            sortOrder: sortedInfo.columnKey === 'employer' && sortedInfo.order,
        }, {
            title: '出校/入校',
            dataIndex: 'enter',
            key: 'enter',
            // filters: this.state.enterStatusArr,
            // onFilter: (value, record) => record.enter.indexOf(value) === 0,
            render: (text, record) => {
                if (text == 'in') {
                    return (<Tag color={'#87d068'}>入校</Tag>)
                } else if (text == 'out') {
                    return (<Tag color={'#108ee9'}>出校</Tag>)
                }
            },
        }, {
            title: '记录时间',
            dataIndex: 'time',
            key: 'time',
            width: winWidth > 1350 ? undefined : 110,
            sorter: (a, b) => new Date(a.time).getTime() - new Date(b.time).getTime(),
            sortOrder: sortedInfo.columnKey === 'time' && sortedInfo.order,
        }, {
            title: '闸机名称',
            dataIndex: 'deviceName',
            key: 'deviceName',
        }, {
            title: '闸机设备IP',
            dataIndex: 'ip',
            key: 'ip',
        }, {
            title: '操作详情',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                return (
                    <span>
                        <a
                            href="javascript:;"
                            onClick={this.showPhoto.bind(this, record.photoUrl)}>
                            查看照片
                        </a>
                    </span>
                )
            },
        }];

        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        let enterStatusOptions = [];
        if (this.state.enterStatusArr.length != 0) {
            enterStatusOptions = this.state.enterStatusArr.map((d, index) =>
                <Option value={d.value} key={index}>{d.text}</Option>
            );
        }

        let deviceNameOptions = [];
        if (this.state.deviceNameArr.length != 0) {
            deviceNameOptions = this.state.deviceNameArr.map((d, index) =>
                <Option value={d} key={index}>{d}</Option>
            );
        }

        let userTypeOptions = [];
        if (this.state.userTypeArr.length != 0) {
            userTypeOptions = this.state.userTypeArr.map((d, index) =>
                <Option value={d.value} key={index}>{d.text}</Option>
            );
        }

        return (
            <div style={{ marginBottom: 16 }}>
                <Spin spinning={this.state.searchOptionLoading} tip="正在加载搜索栏数据..." active>
                    <Form
                        style={{
                            padding: '12px',
                            backgroundColor: '#fafafa',
                            borderRadius: 8,
                            marginBottom: 16,
                        }}
                        layout="inline"
                        onSubmit={this.searchSubmit}>
                        <Row>
                            <Col span={8}>
                                <FormItem
                                    label="姓名"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("name", {
                                        rules: [{
                                            required: false,
                                        }]
                                    })(
                                        <AutoComplete
                                            allowClear={true}
                                            style={{ width: '100%' }}
                                            dataSource={this.state.nameArr}
                                            placeholder="请输入姓名"
                                            filterOption={(inputValue, option) =>
                                                option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem
                                    label="人员编号"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("userNumber", {
                                        rules: [{
                                            required: false,
                                        }]
                                    })(
                                        <AutoComplete
                                            allowClear={true}
                                            style={{ width: '100%' }}
                                            dataSource={this.state.userNumberArr}
                                            placeholder="请输入人员编号"
                                            filterOption={(inputValue, option) =>
                                                option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem
                                    label="人员类别"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("userType", {
                                        rules: [{
                                            required: false,
                                        }]
                                    })(
                                        <Select
                                            allowClear={true}
                                            style={{ width: '100%' }}
                                            placeholder="请选择人员类别">
                                            {userTypeOptions}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8}>
                                <FormItem
                                    label="部门"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("employer", {
                                        rules: [{
                                            required: false,
                                        }]
                                    })(
                                        <AutoComplete
                                            allowClear={true}
                                            style={{ width: '100%' }}
                                            dataSource={this.state.employerArr}
                                            placeholder="请输入部门"
                                            filterOption={(inputValue, option) =>
                                                option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem
                                    label="出/入校"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("enter", {
                                        rules: [{
                                            required: false,
                                        }]
                                    })(
                                        <Select
                                            allowClear={true}
                                            style={{ width: '100%' }}
                                            placeholder="请选择出入校状态">
                                            {enterStatusOptions}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem
                                    label="记录时间"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("timeArr", {
                                        initialValue: [moment(), moment()],
                                        rules: [{
                                            type: 'array',
                                            required: false,
                                        }]
                                    })(
                                        <RangePicker
                                            allowClear={true}
                                            style={{ width: '100%' }}
                                            format="YYYY-MM-DD" />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8}>
                                <FormItem
                                    label="闸机名称"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("deviceName", {
                                        rules: [{
                                            type: 'array',
                                            required: false,
                                        }]
                                    })(
                                        <Select
                                            allowClear={true}
                                            style={{ width: '100%' }}
                                            mode="multiple"
                                            placeholder="请选择闸机名称(可多选)">
                                            {deviceNameOptions}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem
                                    label="闸机ip"
                                    style={{ width: '100%' }}
                                    labelCol={labelCol}
                                    wrapperCol={wrapperCol}>
                                    {getFieldDecorator("ip", {
                                        rules: [{
                                            required: false,
                                        }]
                                    })(
                                        <AutoComplete
                                            allowClear={true}
                                            style={{ width: '100%' }}
                                            dataSource={this.state.ipArr}
                                            placeholder="请输入闸机ip"
                                            filterOption={(inputValue, option) =>
                                                option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem
                                    style={{ float: 'right' }}>
                                    <Button
                                        id='downloadAttendanceSearchResult'
                                        icon="download"
                                        style={{ marginRight: 12 }}
                                        onClick={this.outputSearchResult}>导出结果</Button>
                                    <Button type="primary" htmlType="submit">搜索</Button>
                                    <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Spin>
                {/* <div style={{
                    marginBottom: 16,
                    padding: 16,
                    width: '100%',
                    height: 300,
                    border: '1px solid',
                    borderColor: '#f5f5f5'
                }}>
                    <Skeleton loading={this.state.searchChartLoading} active>
                        {this.state.chartSearchData.timestamp.length == 0 ? (
                            <Empty
                                image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
                                imageStyle={{ marginTop: 60 }}
                                description={
                                    <span style={{ color: '#7a7a7a' }}>结果返回为空，请适当放宽条件搜索</span>
                                }
                            />
                        ) : (
                                <ChartAttendanceRecordSearch
                                    that={this}
                                    chartData={this.state.chartSearchData} />
                            )}
                    </Skeleton>
                </div> */}

                {this.state.isSearch ? (
                    <div>
                        <div style={{
                            marginBottom: 16,
                            padding: 16,
                            width: '100%',
                            height: 300,
                            border: '1px solid',
                            borderColor: '#f5f5f5'
                        }}>
                            <Skeleton loading={this.state.searchChartLoading} active>
                                <ChartAttendanceRecordSearch
                                    that={this}
                                    chartData={this.state.chartAttendanceRecordSearchData} />
                            </Skeleton>
                        </div>
                        <Table
                            dataSource={this.state.tableData}
                            columns={columns}
                            loading={this.state.tableLoading}
                            locale={{ emptyText: '暂无数据' }}
                            onChange={this.handleChange}
                            rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                            pagination={{  //分页
                                total: this.state.tableData.length, //数据总数量
                                defaultPageSize: 10, //默认显示几条一页
                                //pageSize: 10,
                                showTotal: function (total) {  //设置显示一共几条数据
                                    return '共 ' + total + ' 条数据';
                                },
                                showSizeChanger: true,
                                showQuickJumper: true,
                                pageSizeOptions: [5, 10, 20, 30]
                            }} />
                    </div>
                ) : (
                    <Table
                        dataSource={this.state.tableData}
                        columns={columns}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        onChange={this.handleChange}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.tableData.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                )}

                {/* <Modal
                    destroyOnClose
                    visible={this.state.fullScreenVisible}
                    title={'考勤记录搜索结果统计图'}
                    footer={null}
                    width={1000}
                    bodyStyle={{
                        padding: 24,
                        height: 600
                    }}
                    onCancel={() => { this.fullScreenCancel() }}>
                    <div id='fullScreen'
                        style={{
                            width: '100%',
                            height: '100%',
                        }} />
                </Modal> */}
                <Modal
                    destroyOnClose
                    visible={this.state.photoVisible}
                    title={'考勤照片'}
                    footer={null}
                    width={800}

                    bodyStyle={{
                        padding: 24,
                        maxHeight: 600,
                        height: 600,
                        textAlign: 'center'
                    }}
                    onCancel={() => { this.cancelPhoto() }}>
                    <img
                        src={this.state.photoUrl == 'empty' ? require('../img/nophoto.png') : this.state.photoUrl}
                        alt="暂无图片"
                        style={{
                            width: 'auto',
                            height: '100%',
                            maxWidth: '100%',
                        }} />
                </Modal>
            </div>
        )
    }
}
const AttendanceRecord = Form.create()(attendanceRecord);

class ChartAttendanceRecordSearch extends Component {
    constructor(props) {
        super(props);

        this.state = {
            chartData: props.chartData,
            that: props.that,
        };
    }

    componentWillReceiveProps(props) {
        if (JSON.stringify(props.chartData) != JSON.stringify(this.state.chartData)) {
            this.setState({
                chartData: props.chartData,
                that: props.that,
            }, () => {
                this.drawChart();
            })
        }
    }

    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
        if (JSON.stringify(this.state.chartData) != '{}') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('ChartAttendanceRecordSearch'));

            let dataZoom;

            if (this.state.chartData.date.length <= 30) {
                dataZoom = [{
                    type: 'inside',
                    start: 0,
                    end: 100
                }, {
                    start: 0,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            } else {
                dataZoom = [{
                    type: 'inside',
                    start: (this.state.chartData.date.length - 30) / this.state.chartData.date.length * 100,
                    end: 100,
                }, {
                    start: (this.state.chartData.date.length - 30) / this.state.chartData.date.length * 100,
                    end: 100,
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }];
            }


            chart.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['完成计划']
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '40px',
                    top: '30px',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: { show: true, },
                        // restore: { show: true },
                        // dataView: { show: true, readOnly: false },
                        magicType: { show: true, type: ['line', 'bar'] },
                        myFullScreen: {
                            show: true,
                            title: '全屏查看',
                            icon: 'path://M160.762 757.972l210.611-210.61 105.66 105.659-210.644 210.643L362.667 960H64V661.15l96.762 96.822zM266.39 160.336L477.032 370.98 371.373 476.64l-210.61-210.61L64 362.848V64h298.667l-96.278 96.336z m491.222 703.328L546.968 653.02l105.659-105.66 210.61 210.61L960 661.152V960H661.333l96.278-96.336z m105.627-597.636l-210.611 210.61-105.66-105.659 210.644-210.643L661.333 64H960v298.85l-96.762-96.822z',
                            onclick: (e) => {
                                var opts = e.getOption()
                                opts.toolbox[0].feature.myFullScreen.show = false;
                                console.log(this.state)
                                this.state.that.setFullScreen(opts);

                            }
                        }
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: this.state.chartData.date,
                    axisTick: {
                        alignWithLabel: true
                    },
                },
                yAxis: {
                    name: '人数',
                    type: 'value'
                },
                dataZoom: dataZoom,
                series: [{
                    name: '学生进校人数',
                    type: 'line',
                    data: this.state.chartData.studentInTimes,
                    smooth: true,
                    symbol: 'none',
                    sampling: 'average',
                    itemStyle: {
                        color: 'rgb(255, 70, 131)'
                    },
                    areaStyle: {
                        normal: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0, color: 'rgb(255, 158, 68)' // 0% 处的颜色
                                }, {
                                    offset: 1, color: 'rgb(255, 70, 131)' // 100% 处的颜色
                                }],
                                global: false // 缺省为 false
                            },
                        }

                    },
                }, {
                    name: '学生出校人数',
                    type: 'line',
                    data: this.state.chartData.studentOutTimes,
                    smooth: true,
                    symbol: 'none',
                    sampling: 'average',
                    itemStyle: {
                        color: 'rgb(255, 70, 131)'
                    },
                    areaStyle: {
                        normal: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0, color: 'rgb(255, 158, 68)' // 0% 处的颜色
                                }, {
                                    offset: 1, color: 'rgb(255, 70, 131)' // 100% 处的颜色
                                }],
                                global: false // 缺省为 false
                            },
                        }

                    },
                }, {
                    name: '教职工进校人数',
                    type: 'line',
                    data: this.state.chartData.otherRoleOutTimes,
                    smooth: true,
                    symbol: 'none',
                    sampling: 'average',
                    itemStyle: {
                        color: 'rgb(255, 70, 131)'
                    },
                    areaStyle: {
                        normal: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0, color: 'rgb(255, 158, 68)' // 0% 处的颜色
                                }, {
                                    offset: 1, color: 'rgb(255, 70, 131)' // 100% 处的颜色
                                }],
                                global: false // 缺省为 false
                            },
                        }

                    },
                }, {
                    name: '教职工出校人数',
                    type: 'line',
                    data: this.state.chartData.otherRoleInTimes,
                    smooth: true,
                    symbol: 'none',
                    sampling: 'average',
                    itemStyle: {
                        color: 'rgb(255, 70, 131)'
                    },
                    areaStyle: {
                        normal: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0, color: 'rgb(255, 158, 68)' // 0% 处的颜色
                                }, {
                                    offset: 1, color: 'rgb(255, 70, 131)' // 100% 处的颜色
                                }],
                                global: false // 缺省为 false
                            },
                        }

                    },
                }]

            });
            window.onresize = chart.resize;
        }

    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='ChartAttendanceRecordSearch' style={chartStyle} />)
    }
}


/*yuki*/
class attendanceInquiry extends Component {
    constructor(props) {
        super(props);
        this.state = {
            confirmLoading: false,
            departs: [],
            employer: "生物化工系",
            employId: null,
            type: '考勤情况'


        }

    }

    componentDidMount() {
        const avaliable = [];
        const avaliabledepart = []

        const departmentId = sessionStorage.getItem("departmentId");
        AttenceDepartentApi(departmentId).then(res => {
            res.data.forEach((item, index) => {

                avaliable.push({
                    employer: item.employer,
                    employId: item.id,

                });
            });
            for (let i = 0; i < res.data.length; i++) {
                avaliabledepart[i] = avaliable[i].employer;
            }



            this.setState({
                departs: avaliabledepart
            });
        });

    }


    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log('Received values of form: ', values);
            this.setState({
                searchChartLoading: true,
                isSearch: true
            });

            if (values.timePeriod != undefined) {
                values.startDate = values.timePeriod[0].format('YYYY-MM-DD HH:mm:ss');
                values.endDate = values.timePeriod[1].format('YYYY-MM-DD HH:mm:ss');
            }


            const department = parseInt(sessionStorage.getItem("departmentId"));

            if (values.type == 'check') {
                this.setState({
                    chartType: 'check'
                });

                // getHistoryTemperatureApi
                getHistoryCheckApi(department, values)
                    .then((res) => {
                        if (res.data.msg == 'no Data !!!') {
                            notification['warning']({
                                message: '当前条件查询没有数据！',
                                description: '若未填写时间段，则默认查询最近24小时的数据。请检查查询条件，亦或者设备出现问题！',
                                onClick: () => { },
                            });
                            this.setState({
                                searchChartLoading: false,
                                isSearch: false
                            });
                        } else {
                            this.setState({
                                searchChartLoading: false,
                                chartSearchData: res.data,
                            });
                        }

                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
            // else if (values.type == 'in-out') {
            //     this.setState({
            //         chartType: 'ele'
            //     })
            //     getHistoryElectricApi(values)
            //         .then((res) => {
            //             if (res.data.msg == 'no Data !!!') {
            //                 notification['warning']({
            //                     message: '当前条件查询没有数据！',
            //                     description: '请检查查询条件；亦或者设备出现',
            //                     onClick: () => { },
            //                 });
            //                 this.setState({
            //                     searchChartLoading: false,
            //                     isSearch: false
            //                 });
            //             } else {
            //                 this.setState({
            //                     searchChartLoading: false,
            //                     chartSearchData: res.data,
            //                 });
            //             }
            //         })
            //         .catch((e) => {
            //             if (e.response) {
            //                 //请求已发出��服务器返回状态码不是2xx。
            //                 console.info(e.response.data)
            //                 console.info(e.response.status)
            //                 console.info(e.response.headers)
            //             } else if (e.request) {
            //                 // 请求已发出，但没有收到响应
            //                 // e.request 在浏览器里是一个XMLHttpRequest实例，
            //                 // 在node����一个http.ClientRequest实例
            //                 console.info(e.request)
            //             } else {
            //                 //发送请求时异常，捕捉到错误
            //                 console.info('error', e.message)
            //             }
            //             console.info(e.config)
            //         });
            // }
        });
    }

    render() {
        const { getFieldDecorator } = this.props.form;

        const avaliabledepart = this.state.departs.map((d, index) => (
            <Option value={d} key={index}>
                {d}
            </Option>
        ));


        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };


        return (<div style={{ marginBottom: 16 }}>
            <Form
                style={{
                    padding: '12px',
                    backgroundColor: '#fafafa',
                    borderRadius: 8,
                    marginBottom: 16,

                }}
                onSubmit={this.searchSubmit}
            >
                <Row>
                    <Col span={8}>
                        <FormItem
                            label="部门"
                            style={{
                                width: '100%',
                            }}
                            labelCol={labelCol}
                            wrapperCol={wrapperCol}
                            rules={[
                                {
                                    required: true,
                                    message: '部门',
                                },
                            ]}

                        >

                            {(getFieldDecorator("employer", {
                                rules: [
                                    {
                                        required: true,
                                        message: "请选择一个部门"
                                    }
                                ]
                            }
                            )
                            )(
                                <Select
                                    style={{
                                        width: "100%"
                                    }}
                                    size="large"
                                    placeholder="选择部门"
                                >
                                    {avaliabledepart}
                                </Select>)}


                        </FormItem>
                        <FormItem
                            label="类别"
                            style={{
                                width: '100%'
                            }}
                            rules={[
                                {
                                    required: true,
                                    message: '类别',
                                },
                            ]}
                            wrapperCol={wrapperCol}
                            labelCol={labelCol}>
                            {(getFieldDecorator("type", {
                                rules: [
                                    {
                                        required: true,
                                        message: "请选择一个类别"
                                    }
                                ]
                            }
                            )
                            )(
                                <Select style={{ width: '100%' }}
                                    placeholder="请选择搜索类别">
                                    <Option value={'check'}>考勤情况</Option>
                                    <Option value={'in-out'}>进出人数</Option>
                                </Select>)}
                        </FormItem>





                    </Col>
                    <Col span={16}>
                        <FormItem
                            label="时间段"
                            style={{
                                width: '100%',
                            }}
                            labelCol={labelCol}
                            wrapperCol={wrapperCol}
                            rules={[
                                {
                                    required: true,
                                    message: 'Please input your username!',
                                },
                            ]}>
                            {getFieldDecorator("timePeriod", {
                                rules: [{
                                    type: 'array',
                                    required: false,
                                }]
                            })(
                                <RangePicker
                                    style={{ width: '100%' }}

                                    placeholder={['开始时间', '结束时间']}
                                    format="YYYY-MM-DD " />)}
                        </FormItem></Col>

                </Row>
                <Row>
                    <Col span={8}>
                    </Col>
                    <FormItem
                        style={{ float: 'right' }}>
                        <Button type='primary' htmlType="submit" > 搜索</Button>
                        <Button style={{ marginLeft: 8 }} >清空</Button>
                    </FormItem>
                </Row>


            </Form>

            <div>
                <div
                    style={{
                        marginBottom: 16,
                        padding: 16,
                        width: '100%',
                        height: 500,
                        border: '1px solid',
                        borderColor: ' #f5f5f5',

                    }}>


                    {this.state.isSearch ?
                        (
                            <Skeleton loading={this.state.searchChartLoading} active>
                                <AttendanceInquiryechart
                                    that={this}
                                    chartData={this.state.chartSearchData}
                                    type={this.state.chartType} />
                            </Skeleton>
                        ) : (
                            <Empty
                                image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
                                imageStyle={{
                                    marginTop: 170,
                                    marginBottom: 20,
                                }}
                                description={
                                    <span style={{ color: '#7a7a7a' }}>
                                        未接受到数据，请按照条件搜索以展示可视化图表
                                    </span>
                                }
                            />
                        )
                    }
                </div></div>

            <Modal
                destroyOnClose
                visible={this.state.fullScreenVisible}
                title={this.state.chartType == 'tem' ? ('设备温度变化统计图') : ('设备电流变化统计图')}
                footer={null}
                width={1000}
                bodyStyle={{
                    padding: 24,
                    height: 600
                }}
                onCancel={() => { this.fullScreenCancel() }}>
                <div id='fullScreen'
                    style={{
                        width: '100%',
                        height: '100%',
                    }} />
            </Modal>
        </div>






        )
    }


}

const AttendanceInquiry = Form.create()(attendanceInquiry);
class AttendanceInquiryechart extends Component {

    constructor(props) {
        super(props);


        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth)
            winWidth = window.innerWidth;
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;

        this.state = {
            chartData: props.chartData,
            that: props.that,
            winWidth: winWidth,
            type: props.type,
            titleText: '',
            yAxisName: '',
        };
    }






    componentWillReceiveProps(props) {
        if (md5(props.chartData) != md5(this.state.chartData)) {
            this.setState({
                chartData: props.chartData,
                that: props.that,
                type: props.type
            }, () => {
                if (this.state.type == 'check') {
                    this.setState({
                        titleText: '考勤情况',
                        yAxisName: ''
                    }, () => {
                        this.drawChart();
                    })
                } else if (this.state.type == 'in-out') {
                    this.setState({
                        titleText: '电流',
                        yAxisName: '电流(A)'
                    }, () => {
                        this.drawChart();
                    })
                }
            })
        }
    }


    componentDidMount() {

        this.drawchart();

    }

    drawchart() {
        let chart = echarts.init(document.getElementById('xj_charts'));

        let dataZoom = [{
            type: 'inside',
            start: 0,
            end: 10
        }, {
            start: 0,
            end: 10,
            handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
            handleSize: '110%',
            handleStyle: {
                color: "#d3dee5",

            },
        }];

        // import echarts from 'echarts'
        // 按顺序排列从大到小

        chart.setOption({
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                }
            },
            dataZoom: dataZoom,
            toolbox: {
                feature: {
                    dataView: { show: true, readOnly: false },
                    magicType: { show: true, type: ['line', 'bar'] },
                    restore: { show: true },
                    saveAsImage: { show: true }
                }
            },
            legend: {
                data: ['迟到', '早退', '正常']
            },
            xAxis: [
                {
                    type: 'category',
                    data: this.state.chartData.date


                }

            ],
            yAxis:
            {
                type: 'value',
                name: '人数',
                min: 0,
                max: 30,
                interval: 3,
                axisLabel: {
                    formatter: '{value} '
                }
            }
            ,
            series: [
                {
                    name: '迟到',
                    type: 'bar',
                    data: this.state.chartData.late,
                    "barMaxWidth": 55,
                    "barGap": "2%",
                },
                {
                    name: '早退',
                    type: 'bar',
                    "barMaxWidth": 55,
                    "barGap": "2%",
                    data: this.state.chartData.leaveEarly
                },
                {
                    name: '正常',
                    type: 'bar',
                    "barMaxWidth": 55,
                    "barGap": "2%",

                    data: this.state.chartData.normal
                }
            ]
        }

        )
        window.onresize = chart.resize;



    }

    render() {
        return (
            <div id="xj_charts" style={{
                height: '100%',
                width: '97%'
            }}></div>
        );
    }
}

// class attendancesetup extends Component {
//     constructor(props) {
//         super(props);
//         this.state = {
//             members: [],
//             departs:[],
//             schoolId: 0,
//             employer: "生物化工系",
//             fileList: [],
//             uploading: false
//         };
//     }

//     componentDidMount() {
//         const avaliablemembers = [];
//         const avaliabledepart = [];
//         SchoolAllApi().then(res => {
//             res.data.forEach((item, index) => {
//                 //console.log("getAllUser", item);
//                 avaliablemembers.push({
//                     name: item.name,
//                     value: item.id,
//                     address: item.address
//                 });
//             });
//             this.setState({
//                 members: avaliablemembers
//             });
//         });

//         AttenceDepartentApi().then(res => {
//             for(let i=0;i<res.data.length;i++)
//                 avaliabledepart[i]=res.data[i];

//             this.setState({
//                 departs: avaliabledepart
//             });
//         });
//     }
//     handleSubmit = e => {
//         e.preventDefault();
//         const { fileList } = this.state;
//         // console.log(fileList);
//         const formData = new FormData();
//         fileList.forEach(file => {
//             formData.append("upfile", file);
//         });
//         this.setState({
//             uploading: true
//         });

//         this.props.form.validateFields((err, values) => {
//             if (!err) {
//                 formData.append("schoolId", values.schoolId);

//                 formData.append("employer", values.employer);

//                 addInspectItemBySchoolIdApi(formData)
//                     .then(res => {
//                         if (res.data === "success") {
//                             message.success("上传成功！");
//                             this.props.form.resetFields();
//                         } else {
//                             message.error(res.data);
//                         }
//                         this.setState({
//                             uploading: false,
//                             fileList: []
//                         });
//                     })
//                     .catch(e => {
//                         if (e.response) {
//                             //请求已发出，服务器返回状态码不是2xx。
//                             console.info(e.response.data);
//                             console.info(e.response.status);
//                             console.info(e.response.headers);
//                         } else if (e.request) {
//                             // 请求已发出，但没有收到响应
//                             // e.request 在浏览器里是一个XMLHttpRequest实例，
//                             // 在node中是一个http.ClientRequest实例
//                             console.info(e.request);
//                         } else {
//                             //发送请求时异常，捕捉到错误
//                             console.info("error", e.message);
//                         }
//                         console.info(e.config);
//                     });
//             }
//         });
//     };

//     render() {
//         const { uploading, fileList } = this.state;
//         const { getFieldDecorator } = this.props.form;


//         const avaliablemembers = this.state.members.map((d, index) => (
//             <Option value={d.value} key={index}>
//                 {d.name}
//             </Option>
//         ));
//         const avaliabledepart = this.state.departs.map((d, index) => (
//             <Option value={d} key={index}>
//                 {d}
//             </Option>
//         ));
//         const formItemLayout = {
//             labelCol: { span: 8 },
//             wrapperCol: { span: 8 }
//         };

//         const tailFormItemLayout = {
//             wrapperCol: {
//                 offset: 8,
//                 span: 8
//             }
//         };

//         const props = {
//             onRemove: file => {
//                 this.setState(state => {
//                     const index = state.fileList.indexOf(file);
//                     const newFileList = state.fileList.slice();
//                     newFileList.splice(index, 1);
//                     return {
//                         fileList: newFileList
//                     };
//                 });
//             },
//             beforeUpload: file => {
//                 this.setState(state => ({
//                     fileList: [...state.fileList, file]
//                 }));
//                 return false;
//             },
//             fileList
//         };

//         return (
//             <Form {...formItemLayout} onSubmit={this.handleSubmit}>
//                 <Form.Item label="单位">
//                     {getFieldDecorator("schoolId", {
//                         rules: [
//                             {
//                                 required: true,
//                                 message: "请选择一个学校"
//                             }
//                         ]
//                     })(
//                         <Select
//                             style={{
//                                 width: "100%"
//                             }}
//                             size="large"
//                             placeholder="选择学校"
//                         >
//                             {avaliablemembers}
//                         </Select>
//                     )}
//                 </Form.Item>
//                 <Form.Item label="部门">
//                     {getFieldDecorator("employer", {
//                         rules: [
//                             {
//                                 required: true,
//                                 message: "请选择一个部门"
//                             }
//                         ]
//                     })(
//                         <Select
//                             style={{
//                                 width: "100%"
//                             }}
//                             size="large"
//                             placeholder="选择部门"
//                         >
//                             {avaliabledepart}
//                         </Select>
//                     )}
//                 </Form.Item>
//                 <Form.Item label="早班考勤设置">
//                     <RangeTimePicker  defaultValue={moment('8:00', format)} format={format}  style={{width:"47.5%", marginRight:"5%"}}/>
//                     <RangeTimePicker   defaultValue={moment('12:00', format)} format={format}style={{width:"47.5%"}} />



//                 </Form.Item>
//                 <Form.Item label="晚班考勤设置">
//                     <RangeTimePicker  defaultValue={moment('14:00', format)} format={format} style={{width:"47.5%",  marginRight:"5%"}}/>
//                     <RangeTimePicker  defaultValue={moment('18:00', format)} format={format} style={{width:"47.5%" }} />



//                 </Form.Item>



//                 <Form.Item {...tailFormItemLayout}>
//                     <Button type="primary" htmlType="submit">
//                         提交
//                     </Button>
//                 </Form.Item>
//             </Form>
//         );
//     }
// }
// const Attendancesetup = Form.create()(attendancesetup);


class Attendancesetup extends Component {
    constructor(props) {
        super(props);
        this.state = {
            msg: "",
            title: "",
            employid: 0,
            modelVisable: false,
            confirmLoading: false,
            alertVisible: false,
            columnData: [],
            avaliable: [],
            tableLoading: false,
            filteredInfo: null,
            sortedInfo: null,
            unusedDepartList: [],
            department: null,
            startTime: null,
            endTime: null,
            electricalthreshold: null,
            temperaturethreshold: null,
            modelType: null,
        };
    }

    componentDidMount() {
        this.refreshData()
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];

        let department = parseInt(sessionStorage.getItem("departmentId"));
        getattendanceSettimeListApi(department)
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({

                        key: index + 1,

                        employer: item.employ,
                        startTime: item.startTime,
                        endTime: item.endTime,

                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });


        const avaliable = [];
        const unusedDepartList = [];
        const departmentId = sessionStorage.getItem("departmentId");
        AttenceDepartentApi(departmentId).then(res => {



            for (let i = 0; i < res.data.length; i++)


                unusedDepartList[i] = res.data[i].id + "-" + res.data[i].employer;
            this.setState({
                unusedDepartList: unusedDepartList,
                avaliable: avaliable
                // eslint-disable-next-line indent
            })
        })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleDelete(department, employ) {
        // deleteGpsFireElectricApi
        deleteaddAttendanceTimeApi(department, employ)
            .then((res) => {
                if (res.data == "success") {
                    message.success("删除成功!");
                    this.refreshData();
                } else {
                    message.error('删除失败,请稍后再试!');
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        this.setState({ searchText: selectedKeys[0] });
    }

    handleReset = clearFilters => () => {
        clearFilters();
        this.setState({ searchText: '' });
    }

    showModal(type, record) {

        console.log(record)
        if (type == "add") {
            this.setState({
                modelVisable: true,
                title: "新增部门考勤",
                department: null,
                startTime: null,
                endTime: null,

                modelType: "add",
            })
        }
        if (type == "update") {

            console.log("sss" + record)
            this.setState({
                modelVisable: true,
                title: "修改考勤时间",
                employ: record.employer,
                startTime: record.startTime,

                endTime: record.endTime,
                modelType: "update",
            })
        }
    }

    handleCancel() {
        this.setState({
            modelVisable: false
        })
    }

    commitForm() {
        this.setState({
            confirmLoading: true,
            tableLoading: true,
        });
        let val = this.refs.attendanceDepolyForm;
        val.validateFields((err, values) => {



            // }
            if (!err)

                if (this.state.modelType == "add") {


                    let that = this;
                    values.startTime = values.startTime.format('HH:mm:ss ');
                    values.endTime = values.endTime.format('HH:mm:ss ');

                    let employid = parseInt(values.employ.split("-")[0]);
                    values.employ = values.employ.split("-")[1];
                    const department = parseInt(sessionStorage.getItem("departmentId"));

                    // addGpsFireElectricDeviceApi
                    addAttendanceTimeApi(department, employid, values)
                        .then(res => {

                            if (moment(values.endTime).isBefore(values.startTime)) {
                                that.setState({ confirmLoading: false });
                                message.error("结束时间不能早于开始时间");


                            } else if (res.data == "suceess") {
                                message.success("新增考勤成功");
                                this.handleCancel(); //关闭模态框
                                this.refreshData();
                            } else if (res.data == "contained") {
                                message.error("部门已设置考勤时间");
                            } else {
                                message.error("新增失败，请检查填写情况");
                            }
                            this.setState({
                                confirmLoading: false,
                                tableLoading: false,
                            });
                        })
                        .catch((e) => {
                            if (e.response) {
                                //请求已发出，服务器返回状态码不是2xx。
                                console.info(e.response.data)
                                console.info(e.response.status)
                                console.info(e.response.headers)
                            } else if (e.request) {
                                // 请求已发出，但没有收到响应
                                // e.request 在浏览器里是一个XMLHttpRequest实例，
                                // 在node中是一个http.ClientRequest实例
                                console.info(e.request)
                            } else {
                                //发送请求时异常，捕捉到错误
                                console.info('error', e.message)
                            }
                            console.info(e.config)
                        });
                }
                else {
                    let that = this;
                    values.startTime = values.startTime.format('HH:mm:ss  ');
                    values.endTime = values.endTime.format('HH:mm:ss ');

                    let employid = parseInt(values.employ.split("-")[0]);
                    values.employ = values.employ.split("-")[1];

                    updateAttendanceTimeApi(sessionStorage.getItem("departmentId"), employid, values)
                        .then(res => {
                            if (res.data == "success") {
                                message.success("修改成功！");
                                this.handleCancel(); //关闭模态框
                                this.refreshData();
                            } else {
                                message.error("修改失败，请检查填写是否重复");
                            }
                            this.setState({
                                confirmLoading: false,
                                tableLoading: false,
                            });
                        })
                        .catch((e) => {
                            if (e.response) {
                                //请求已发出，服务器返回状态码不是2xx。
                                console.info(e.response.data)
                                console.info(e.response.status)
                                console.info(e.response.headers)
                            } else if (e.request) {
                                // 请求已发出，但没有收到响应
                                // e.request 在浏览器里是一个XMLHttpRequest实例，
                                // 在node中是一个http.ClientRequest实例
                                console.info(e.request)
                            } else {
                                //发送请求时异常，捕捉到错误
                                console.info('error', e.message)
                            }
                            console.info(e.config)
                        });

                }
        })
    }

    render() {
        console.log(this.state.columnData)
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const userColumns = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "部门",
                dataIndex: "employer",
                key: "employer"
            },
            {
                title: "开始考勤时间",
                dataIndex: "startTime",
                key: "startTime",
            },
            {
                title: "结束考勤时间",
                dataIndex: "endTime",
                key: "endTime"
            },

            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        <a href="javascript:;" onClick={() => this.showModal("update", record)}>修改</a>
                        <Divider type="vertical" />
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消"
                            onConfirm={() => this.handleDelete(sessionStorage.getItem("departmentId"), record.employer)}>
                            <a href="#">删除</a>
                        </Popconfirm>
                    </span>
                )
            }
        ];
        return (
            <div>
                <div style={{ marginBottom: 16 }}>
                    <Button type="primary" onClick={() => this.showModal("add")} size="large">
                        <Icon type="icon-kaoqin" />新增考勤
                    </Button>
                    <Modal
                        title={this.state.title}
                        destroyOnClose={true}
                        visible={this.state.modelVisable}
                        onCancel={() => this.handleCancel()}
                        closable
                        footer={[
                            <Button key="submit" type="primary" size="large"
                                loading={this.state.confirmLoading}
                                onClick={() => this.commitForm()}>提交</Button>
                        ]}
                    >
                        <AttendanceDepolyForm ref="attendanceDepolyForm" temperaturethreshold={this.state.temperaturethreshold} electricalthreshold={this.state.electricalthreshold} department={this.state.department} unusedDepartList={this.state.unusedDepartList} />
                    </Modal>
                </div>
                <Table
                    dataSource={this.state.columnData}
                    columns={userColumns}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    pagination={{  //分页
                        defaultPageSize: 10, //默认显示几条一页
                        pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        );
    }
}

class attendanceDepolyForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            DepartList: this.props.unusedDepartList == undefined ? undefined : this.props.unusedDepartList,
            department: this.props.department == undefined ? undefined : this.props.department,

            electricalthreshold: this.props.electricalthreshold == undefined ? undefined : this.props.electricalthreshold,
            temperaturethreshold: this.props.temperaturethreshold == undefined ? undefined : this.props.temperaturethreshold,
        };
    }

    componentDidMount() {
        this.onChange();
    }

    onChange(time, timeString) {
        console.log(time, timeString);
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        };
        let IMEIOptions = []


        IMEIOptions = this.state.DepartList.map((d, index) => (
            <Option value={d} key={index}>
                {d}
            </Option>
        ))
        return (
            <Form>
                <FormItem
                    label='部门'
                    {...formItemLayout}
                >
                    {getFieldDecorator("employ", {
                        initialValue: this.state.department,
                        rules: [{
                            required: true,
                            message: "请选择部门!"
                        }]
                    })(
                        <Select
                            mode="single"
                            size="large"
                            placeholder="选择部门">
                            {IMEIOptions}
                        </Select>
                    )}
                </FormItem>

                <FormItem
                    label='开始时间'
                    {...formItemLayout}>
                    {getFieldDecorator("startTime", {
                        initialValue: moment('08:00:00', "HH:mm:ss"),
                        rules: [{
                            required: true,
                            message: "请选择开始时间!"
                        }]
                    })(
                        <TimePicker format="HH:mm:ss "
                            defaultValue={moment('08:00:00', "HH:mm:ss")}
                            style={{ width: "100%" }}
                            size="large"
                            prefix={
                                <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
                            }

                        />
                    )}
                </FormItem>
                <FormItem
                    label='结束时间'
                    {...formItemLayout}>
                    {getFieldDecorator("endTime", {
                        initialValue: moment('17:00:00', "HH:mm:ss"),
                        rules: [{
                            required: true,
                            message: "请选择结束时间!"
                        }]
                    })(
                        <TimePicker format="HH:mm:ss"
                            defaultValue={moment('17:00:00', "HH:mm:ss")}
                            style={{ width: "100%" }}
                            size="large"
                            prefix={
                                <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
                            }

                        />
                    )}
                </FormItem>
            </Form>
        )
    }
}
const AttendanceDepolyForm = Form.create()(attendanceDepolyForm);










export default SchoolAdmin;
export {
    SchoolUserManager, BlueteethDeviceManager, SchoolAddressManager, AddressWithBlueteethManager, SchoolManualManager,
    SchoolMessagepushManager, SchoolInspectpushManager, SchoolSafetyscenePushManager, SchoolBlueTeethManager,
    SchoolEventPushManager, SchoolKaoQinPushManager, SchoolZhiZhouPushManager,
    SchoolEmergencyManager, SignBlueteeth, AttendanceSchedule, AttendanceRecord, AttendanceInquiry, Attendancesetup
}